Imports System
Imports MindFusion.Diagramming
Imports MindFusion.Diagramming.TableNode
Imports MindFusion.Drawing
Imports DevExpress.XtraTreeList.Nodes
Imports DevExpress.Utils
Imports DevExpress.XtraEditors.Repository
Imports DevExpress.XtraTreeList.Columns
Imports DevExpress.XtraTreeList

Public Class MainForm

#Region "Attributes"
#Region "Private attributes"
    Private WithEvents MoApplicationFile As ClsFileOfApplication = New ClsFileOfApplication 'file of application (EXE file)
    Private WithEvents MoAmodFile As ClsFileAmod = New ClsFileAmod 'aMod file
    Private WithEvents MoUserSettingsFile As ClsUserSettings = New ClsUserSettings 'user settings file
    Private WithEvents MoHand As ClsHand 'represents mouse action - what is user performing by mouse
#End Region
#End Region
#Region "Constructors"
    Public Sub New()
        ' This call is required by the Windows Form Designer.

        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        'registering of my class for serialization, XML save/load,...
        Diagram.RegisterItemClass(GetType(ClsMMContainerNode), "ClsMMContainerNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMLinkNode), "ClsMMLinkNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMShapeNode), "ClsMMShapeNode", 1)
        Diagram.RegisterItemClass(GetType(ClsMMTableNode), "ClsMMTableNode", 1)
    End Sub
#End Region
#Region "Events handler"
#Region "XtraForm1 - Events handler"
    'loading of XtraForm1
    Private Sub XtraForm1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        InitializeApplication()
        SetSettingsBeforeApplicationStarts()
    End Sub
    'closing apllication
    Private Sub XtraForm_Closing(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles MyBase.Closing
        Dim LbCanClose As Boolean = False

        LbCanClose = Not CanExitApplication()

        If Not LbCanClose Then
            SaveUserSettingsToFile()
        End If

        e.Cancel = LbCanClose
    End Sub
    '' ''keypress on XtraForm1
    ' ''Private Sub XtraForm1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles Me.KeyPress
    ' ''    'since Me.KeyPreview = True Im in this metod :-). Send it to fcDiagramView_KeyPress
    ' ''    fcDiagramView_KeyPress(sender, e)
    ' ''End Sub
#End Region
#Region "Buttons - Events handler"
    'switching on zomming
    Private Sub btnZoomToRect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnZoomToRect.Click
        MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkZoom
    End Sub
#End Region
#Region "fcDiagram - Events handler"
    'show properties of tables row
    Private Sub fcDiagram_CellClicked(ByVal sender As Object, ByVal e As MindFusion.Diagramming.CellEventArgs) Handles fcDiagram.CellClicked
        Debug.Print("fcDiagram_CellClicked")

        Dim LoMMTableNode As ClsMMTableNode = e.Table
        If MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkIdle Then
            If LoMMTableNode IsNot Nothing Then
                RefreshSelectedItemProperties(LoMMTableNode, e.Row)
            End If
        End If
    End Sub
    'initialization of node
    Private Sub fcDiagram_InitializeNode(ByVal sender As Object, ByVal e As MindFusion.Diagramming.NodeEventArgs) Handles fcDiagram.InitializeNode
        Debug.Print("Diagram_InitializeNode")
        Debug.Print(e.Node.GetType().Name.ToString)

        If MoHand.SecondaryOperation <> GeSecondaryOperationOfHand.kkIdle Then
            'there is any secondary operation
            Select Case MoHand.SecondaryOperation
                Case GeSecondaryOperationOfHand.kkZoom
                    Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassRECTANGLE.cur")
                    Dim LoNode As ShapeNode = CType(e.Node, ShapeNode)
                    LoNode.Shape = Shapes.Rectangle
                    LoNode.Pen = New Pen(Color.LightGray, 1)
                    LoNode.Brush = New SolidBrush(Color.Transparent)
                    LoNode.ShadowColor = Color.Transparent
                    LoNode.Text = "Tahanim zvolte oblast pre priblizenie..."
                Case Else
                    Debug.Print("CHYBA!!! - fcDiagram_InitializeNode")
            End Select
        Else
            'some node is creating
            Select Case e.Node.GetType.Name
                Case "ClsMMTableNode"
                    CType(e.Node, ClsMMTableNode).MMSetDefaultProperties()
                Case "ClsMMContainerNode"
                    CType(e.Node, ClsMMContainerNode).MMSetDefaultProperties()
            End Select
        End If
    End Sub
    'perform secondary zooming operation 
    Private Sub fcDiagram_NodeCreated(ByVal sender As Object, ByVal e As MindFusion.Diagramming.NodeEventArgs) Handles fcDiagram.NodeCreated
        Debug.Print("fcDiagram_NodeCreated")

        If MoHand.SecondaryOperation <> GeSecondaryOperationOfHand.kkIdle Then
            Select Case MoHand.SecondaryOperation
                Case GeSecondaryOperationOfHand.kkZoom
                    Dim node As ShapeNode = CType(e.Node, ShapeNode)
                    fcDiagramView.ZoomToRect(node.Bounds)
                    fcDiagram.Nodes.Remove(node)
                    Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassNORMAL.cur")
                Case Else
                    Debug.Print("CHYBA!!! - fcDiagram_NodeCreated")
            End Select
        End If
    End Sub
    'perform fitting of size of table for any types of modification
    Private Sub fcDiagram_NodeModifying(ByVal sender As Object, ByVal e As MindFusion.Diagramming.NodeValidationEventArgs) Handles fcDiagram.NodeModifying
        MoAmodFile.FileWasModified = True

        Select Case e.AdjustmentHandle
            Case AdjustmentHandles.ResizeBottomCenter, AdjustmentHandles.ResizeBottomLeft, _
                 AdjustmentHandles.ResizeBottomRight, AdjustmentHandles.ResizeMiddleLeft, AdjustmentHandles.ResizeMiddleRight, _
                 AdjustmentHandles.ResizeTopCenter, AdjustmentHandles.ResizeTopLeft, AdjustmentHandles.ResizeTopRight
                Select Case e.Node.GetType.Name
                    Case "ClsMMTableNode"
                        CType(e.Node, ClsMMTableNode).MMResizeAllToFitTable(False)
                    Case "ClsMMContainerNode"
                        CType(e.Node, ClsMMContainerNode).MMResizeHeightOfCaption()
                End Select
            Case AdjustmentHandles.Move
                Select Case e.Node.GetType.Name
                    Case "ClsMMTableNode"
                        Dim LoPointF As PointF = fcDiagramView.ClientToDoc(fcDiagramView.PointToClient(Control.MousePosition))
                        Dim LoContainerForTable As ClsMMContainerNode = AllowDropNodeOutsideOfContainer(LoPointF)

                        If LoContainerForTable Is Nothing Then
                            e.Cancel = True
                            Debug.Print("nastavujem TRUE")
                        Else
                            e.Cancel = False
                            Debug.Print("nastavujem FALSE")
                            Me.fcDiagramView.CurrentCursor = Cursors.SizeAll
                        End If

                        Debug.Print(e.Cancel)
                End Select
        End Select
    End Sub
    'resize node after resizing (by moving or resizing)
    Private Sub fcDiagram_NodeModified(ByVal sender As Object, ByVal e As MindFusion.Diagramming.NodeEventArgs) Handles fcDiagram.NodeModified
        Select Case e.Node.GetType.Name
            Case "ClsMMTableNode"
                CType(e.Node, ClsMMTableNode).MMResizeAllToFitTable(True) 'resizing table and parent container
            Case "ClsMMContainerNode"
                CType(e.Node, ClsMMContainerNode).MMResizeHeightOfCaption() 'resize height of container caption
        End Select
    End Sub
    'cancel selection of node if secondary operation is ZOOM
    Private Sub fcDiagram_NodeSelecting(ByVal sender As Object, ByVal e As MindFusion.Diagramming.NodeValidationEventArgs) Handles fcDiagram.NodeSelecting
        If MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkZoom Then e.Cancel = True
    End Sub
    'deselecting row of table
    Private Sub fcDiagram_NodeDeactivated(ByVal sender As Object, ByVal e As MindFusion.Diagramming.NodeEventArgs) Handles fcDiagram.NodeDeactivated
        Debug.Print("fcDiagram_NodeDeactivated")

        Dim LoItem As DiagramItem = e.Node
        If LoItem IsNot Nothing Then
            Select Case LoItem.GetType.Name
                Case "ClsMMTableNode"
                    'deselecting row of table
                    Dim LoMMTableNode As ClsMMTableNode = CType(LoItem, ClsMMTableNode)
                    LoMMTableNode.HighlightedRow = -1
            End Select
        End If
    End Sub
    'set type of link and its default properties
    Private Sub fcDiagram_InitializeLink(ByVal sender As Object, ByVal e As MindFusion.Diagramming.LinkEventArgs) Handles fcDiagram.InitializeLink
        Debug.Print("fcDiagram_InitializeLink")
        Dim LoMMLinkNode As ClsMMLinkNode = CType(e.Link, ClsMMLinkNode)

        'setting type of link
        Select Case e.Link.Origin.GetType.Name
            Case "ClsMMTableNode"
                LoMMLinkNode.MMTypeOfLink = GeTypeOfLink.kkRelationship
                LoMMLinkNode.MMRelationType = MoHand.TypeOfLink
            Case "ClsMMShapeNode"
                LoMMLinkNode.MMTypeOfLink = GeTypeOfLink.kkNote
                LoMMLinkNode.MMRelationType = kkRelationTypes.kkNone
            Case Else
                Debug.Print("CHYBA!!! - fcDiagram_InitializeLink")
        End Select
    End Sub
    'prevent to create loop link while creating a link
    Private Sub fcDiagram_LinkCreating(ByVal sender As Object, ByVal e As MindFusion.Diagramming.LinkValidationEventArgs) Handles fcDiagram.LinkCreating
        Debug.Print("fcDiagram_LinkCreating")

        Dim LoMMLinkNode As ClsMMLinkNode = CType(e.Link, ClsMMLinkNode)
        e.Cancel = Not CheckLinkRules(LoMMLinkNode, e.Node, e.Origin, e.Destination, False)
    End Sub
    'set links properties after link is created
    Private Sub fcDiagram_LinkCreated(ByVal sender As Object, ByVal e As MindFusion.Diagramming.LinkEventArgs) Handles fcDiagram.LinkCreated
        Debug.Print("fcDiagram_LinkCreated")

        Dim LoMMLinkNode As ClsMMLinkNode = CType(e.Link, ClsMMLinkNode)

        Select Case LoMMLinkNode.MMTypeOfLink
            Case GeTypeOfLink.kkRelationship
                Dim LoAction As ClsAction = New ClsAction(GeAction.kkAddLinkToDiagram)
                LoAction.SetData(LoMMLinkNode, "LINK")

                If Execute(LoAction) = GeActionResult.kkOk Then
                    'setting new settings after link is created
                    LoMMLinkNode.SnapToNodeBorder = True
                    LoMMLinkNode.AutoRoute = True
                    LoMMLinkNode.Style = LinkStyle.Cascading
                Else
                    'deleting link after unsuccessfully added to dataset
                    Me.fcDiagram.Links.Remove(LoMMLinkNode)
                End If

            Case GeTypeOfLink.kkNote
                'setting new settings after link is created
                LoMMLinkNode.SnapToNodeBorder = True
                LoMMLinkNode.AutoRoute = False
                LoMMLinkNode.Style = LinkStyle.Polyline
                MoAmodFile.FileWasModified = True
            Case Else
                Debug.Print("CHYBA!!! - fcDiagram_LinkCreated")
        End Select
    End Sub
    'prevent to create loop link while modifying a link
    Private Sub fcDiagram_LinkModifying(ByVal sender As Object, ByVal e As MindFusion.Diagramming.LinkValidationEventArgs) Handles fcDiagram.LinkModifying
        Debug.Print("fcDiagram_LinkModifying")

        Dim LoMMLinkNode As ClsMMLinkNode = CType(e.Link, ClsMMLinkNode)
        e.Cancel = Not CheckLinkRules(LoMMLinkNode, e.Node, e.Origin, e.Destination, True)
    End Sub
    'resize item after it was added to diagram. Raised when an item is added to the diagram, either programmatically or interactively!
    Private Sub fcDiagram_ItemAdded(ByVal sender As Object, ByVal e As MindFusion.Diagramming.ItemEventArgs) Handles fcDiagram.ItemAdded
        Select Case e.Item.GetType.Name
            Case "ClsMMTableNode"
                CType(e.Item, ClsMMTableNode).MMResizeAllToFitTable()
        End Select
    End Sub
    'node was added to container
    Private Sub fcDiagram_ContainerChildAdded(ByVal sender As Object, ByVal e As MindFusion.Diagramming.ContainerChildEventArgs) Handles fcDiagram.ContainerChildAdded
        Debug.Print("fcDiagram_ContainerChildAdded")
        CType(e.Container, ClsMMContainerNode).MMResizeAllToFitContainer()
    End Sub
    'node was removed from container
    Private Sub fcDiagram_ContainerChildRemoved(ByVal sender As Object, ByVal e As MindFusion.Diagramming.ContainerChildEventArgs) Handles fcDiagram.ContainerChildRemoved
        Debug.Print("fcDiagram_ContainerChildRemoved")
        CType(e.Container, ClsMMContainerNode).MMResizeAllToFitContainer()
    End Sub
    'check if actual validating anchorpoint is valid (free) for accepting a new link
    'ATTENTION! Raised when shape is moving too !!!
    Private Sub fcDiagram_ValidateAnchorPoint(ByVal sender As Object, ByVal e As MindFusion.Diagramming.LinkValidationEventArgs) Handles fcDiagram.ValidateAnchorPoint
        'Debug.Print("fcDiagram_ValidateAnchorPoint")
        If Not IsFreeAnchorPoint(e.Node, e.Link, e.AnchorIndex, 1) Then
            e.Cancel = True
        End If
    End Sub
    'refresh selected item properties in properties treelist
    Private Sub fcDiagram_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles fcDiagram.SelectionChanged
        Debug.Print("fcDiagram_SelectionChanged")
        RefreshSelectedItemProperties(Me.fcDiagram.ActiveItem)
    End Sub
#End Region
#Region "fcDiagramView - Events handler"
    'drag drop fcDiagramView event
    Private Sub fcDiagramView_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles fcDiagramView.DragDrop
        If e.Data.GetDataPresent(ClsDragDropItem.GetTypeOfItem()) Then
            Dim LoPoint As Point = fcDiagramView.PointToClient(New Point(e.X, e.Y))
            Dim LoPointF As PointF = fcDiagramView.ClientToDoc(New Point(LoPoint.X, LoPoint.Y))

            Dim LoDragDropItem As ClsDragDropItem = e.Data.GetData(ClsDragDropItem.GetTypeOfItem)
            Dim LeResult As GeActionResult = GeActionResult.kkError
            Dim LbTable As Boolean = False 'true if table is adding
            Dim LbTemplate As Boolean = False 'true if template is adding
            Dim LoNode As DiagramNode = Nothing

            Dim LoContainerForTable As ClsMMContainerNode = Nothing

            Dim LoAction As ClsAction = New ClsAction(GeAction.kkAddItemToDiagram)

            Select Case LoDragDropItem.TypeOfDragDropItem
                Case GeTypeOfDragDropItem.kkNone
                    LoNode = Nothing
                Case GeTypeOfDragDropItem.kkTable
                    LoContainerForTable = AllowDropNodeToContainer(LoPointF)
                    If LoContainerForTable IsNot Nothing Then
                        LbTable = True
                        Dim LsNameOfContainer As String = LoContainerForTable.Caption
                        LoNode = CreateNewNode(GePrimaryOperationOfHand.kkTable)
                        LoAction.SetData("Class", "ORIGINALAPPTABLENAME")
                        LoAction.SetData(LoContainerForTable, "CONTAINER")
                    Else
                        Debug.Print("CHYBA!!! - fcDiagramView_DragDrop - Case kkTable")
                    End If

                Case GeTypeOfDragDropItem.kkContainer
                    LoNode = CreateNewNode(GePrimaryOperationOfHand.kkContainer)
                    LoAction.SetData("Formular", "ORIGINALCONTAINERNAME")
                    LoAction.SetData("Class", "ORIGINALAPPTABLENAME")

                Case GeTypeOfDragDropItem.kkNote
                    LoNode = CreateNewNode(GePrimaryOperationOfHand.kkNote)

                Case GeTypeOfDragDropItem.kkTemplateTable
                    LoContainerForTable = AllowDropNodeToContainer(LoPointF)
                    If LoContainerForTable IsNot Nothing Then
                        LbTable = True
                        LbTemplate = True
                        Dim LsNameOfContainer As String = LoContainerForTable.Caption
                        LoNode = UcnNodesToolbarUC.GetTemplate(UcnNodesToolbarUC.GetNameOfTemplate)
                        Dim LoNodeNew As ClsMMTableNode = New ClsMMTableNode(LoNode)
                        LoNode = LoNodeNew
                        LoAction.SetData(LoNodeNew.Caption, "ORIGINALAPPTABLENAME")
                        LoAction.SetData(LoContainerForTable, "CONTAINER")
                    End If

                    ''set flag for later use
                    'LbTemplate = True
                    'LoNode = UcnNodesToolbarUC.GetTemplate(UcnNodesToolbarUC.GetNameOfTemplate)
                    ''creating new table from prototype
                    'Dim LoNodeNew As ClsMMTableNode = New ClsMMTableNode(LoNode)
                    'LoNode = LoNodeNew
                    'LoAction.SetData(LoNodeNew.Caption, "ORIGINALAPPTABLENAME")
                Case Else
                    LoNode = Nothing
                    Debug.Print("CHYBA!!! - fcDiagramView_DragDrop - Select Case")
            End Select

            If LoNode IsNot Nothing Then
                LoNode.Bounds = SDRectangleFVirginCreator(LoPointF.X, LoPointF.Y, LoNode.Bounds.Width, LoNode.Bounds.Height)
                'add item to DS and then to the diagram
                LoAction.SetData(LoNode, "ITEM")
                LeResult = Execute(LoAction)
            End If

            If LeResult = GeActionResult.kkOk And LbTemplate Then
                'in case of adding template add rows to DS
                Dim LoClsTableNode As ClsMMTableNode = CType(LoNode, ClsMMTableNode)
                Dim LoDataTable As DataTable = CType(LoClsTableNode.Tag, DataTable)
                'clearing tag
                LoClsTableNode.Tag = Nothing

                Try
                    For Each LoDataRow As DataRow In LoDataTable.Rows
                        Dim LoNewRow As DataRow = MoAmodFile.Dataset.Tables("_a_Columns").NewRow
                        LoNewRow.ItemArray = LoDataRow.ItemArray
                        'LoNewRow.Item("AppTableName") = LoClsTableNode.Caption
                        LoNewRow.Item("TableName") = MoAmodFile.GetTableNameFromAppTableName(LoClsTableNode.Caption)
                        MoAmodFile.Dataset.Tables("_a_Columns").Rows.Add(LoNewRow)
                    Next
                Catch ex As Exception
                    Debug.Print("CHYBA!!! - table from toolbar")
                End Try
            End If

            ' ''If LeResult = GeActionResult.kkOk Then
            ' ''    'resizing node after inserting to diagram
            ' ''    Select Case LoNode.GetType.Name
            ' ''        Case "ClsMMTableNode"
            ' ''            CType(LoNode, ClsMMTableNode).MMResizeAllToFitTable()
            ' ''    End Select
            ' ''End If
        End If
    End Sub
    'drag over fcDiagramView event
    Private Sub fcDiagramView_DragOver(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles fcDiagramView.DragOver
        'If IsThereDataForDragDrop(e.Data) Then
        If e.Data.GetDataPresent(ClsDragDropItem.GetTypeOfItem()) Then
            Dim LoDragDropItem As ClsDragDropItem = e.Data.GetData(ClsDragDropItem.GetTypeOfItem)
            If LoDragDropItem.TypeOfDragDropItem = GeTypeOfDragDropItem.kkTable Or LoDragDropItem.TypeOfDragDropItem = GeTypeOfDragDropItem.kkTemplateTable Then
                Dim pt As Point = fcDiagramView.PointToClient(New Point(e.X, e.Y))
                Dim ptF As PointF = fcDiagramView.ClientToDoc(New Point(pt.X, pt.Y))
                If AllowDropNodeToContainer(ptF) IsNot Nothing Then
                    e.Effect = DragDropEffects.Copy
                Else
                    e.Effect = DragDropEffects.None
                End If
            Else
                e.Effect = DragDropEffects.Copy
            End If
        Else
            e.Effect = DragDropEffects.None
        End If
    End Sub
    'keydown on fcDiagramView
    Private Sub fcDiagramView_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles fcDiagramView.KeyDown
        'only for delete key!
        Select Case e.KeyCode
            Case Keys.Delete 'DEL
                If Me.fcDiagramView.Diagram.ActiveItem IsNot Nothing Then
                    Dim LoAction As ClsAction = New ClsAction(GeAction.kkDeleteDiagramSelection)
                    Execute(LoAction)
                End If
        End Select
    End Sub
    'keypress on fcDiagramView
    Private Sub fcDiagramView_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles fcDiagramView.KeyPress
        Select Case Asc(e.KeyChar)
            Case Keys.Escape 'ESC
                'cancel zoom secondary operation
                If MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkZoom Then
                    MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkIdle
                End If
        End Select
    End Sub
    'perform click action (zooming, tables row properties, context menu,...)
    Private Sub fcDiagramView_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles fcDiagramView.MouseClick
        Debug.Print("fcDiagramView_MouseClick")

        Select Case e.Button
            Case Windows.Forms.MouseButtons.Left
                'zooming secondary operation
                If MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkZoom Then
                    Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassNORMAL.cur")
                    ZoomToPoint(Cursor.Position, 500)
                    Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassPLUS.cur")
                End If
            Case Windows.Forms.MouseButtons.Right
                If MoHand.SecondaryOperation <> GeSecondaryOperationOfHand.kkIdle Then
                    'perform secondary operation
                    Select Case MoHand.SecondaryOperation
                        Case GeSecondaryOperationOfHand.kkZoom
                            Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassNORMAL.cur")
                            ZoomToPoint(Cursor.Position, -500)
                            Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassMINUS.cur")
                    End Select
                Else
                    'show popup menu for table
                    Dim LoItem As DiagramItem = fcDiagram.GetItemAt(fcDiagramView.ClientToDoc(e.Location), True)

                    If LoItem IsNot Nothing Then
                        Select Case LoItem.GetType.Name
                            Case "ClsMMTableNode"
                                ShowPopupMenu(GeTypeOfPopupMenu.kkNodeContext, fcDiagramView.PointToScreen(e.Location))
                            Case "ClsMMContainerNode"
                                ShowPopupMenu(GeTypeOfPopupMenu.kkUnitContext, fcDiagramView.PointToScreen(e.Location))
                        End Select
                    End If
                End If
        End Select
    End Sub
    'creating, filling and assigning inplace editors for editing of nodes cells
    Private Sub fcDiagramView_CreateEditControl(ByVal sender As Object, ByVal e As MindFusion.Diagramming.WinForms.InPlaceEditEventArgs) Handles fcDiagramView.CreateEditControl
        Debug.Print("fcDiagramView_CreateEditControl")

        Dim LoEditRectangle As RectangleF = e.Item.GetEditRect(PointF.Empty)

        Select Case e.Item.GetType.Name
            Case "ClsMMTableNode"
                Dim LoMMTableNode As ClsMMTableNode = CType(e.Node, ClsMMTableNode)
                If Not LoMMTableNode Is Nothing Then
                    Me.txtInPlaceEditor.Text = LoMMTableNode.Caption
                End If
            Case "Cell"
                Dim LoCell As TableNode.Cell = CType(e.Item, TableNode.Cell)
                If Not LoCell Is Nothing Then
                    Me.txtInPlaceEditor.Text = LoCell.Text
                End If
            Case "ClsMMShapeNode"
                'Dim LoMMShapeNode As ClsMMShapeNode = CType(e.Node, ClsMMShapeNode)
                Dim a As RichTextBox = New RichTextBox
                e.EditControl = a
                a.Visible = True
                e.Item.SetEditedText("ABC")
                Dim docRect As RectangleF = e.Item.GetEditRect(PointF.Empty)
                a.Bounds = fcDiagramView.DocToClient(docRect)
        End Select

        If e.Item.GetType.Name = "ClsMMTableNode" Or e.Item.GetType.Name = "Cell" Then
            Me.txtInPlaceEditor.Bounds = Me.fcDiagramView.DocToClient(LoEditRectangle)
            Me.txtInPlaceEditor.Visible = True
            'since Im using my own editcontrol (DevExpress.XtraEditors.TextEdit) 
            'theres a problem with EndEdit method and it is hard to determine if change is accepted.
            'So I set value to Tag property for further use indicated not/accepting changes
            Me.txtInPlaceEditor.Tag = CBool("TRUE")
            Me.txtInPlaceEditor.Focus()
            e.EditControl = Me.txtInPlaceEditor
        End If
    End Sub
    'destroying and not/accepting changes after inplace edit
    Private Sub fcDiagramView_DestroyEditControl(ByVal sender As Object, ByVal e As MindFusion.Diagramming.WinForms.InPlaceEditEventArgs) Handles fcDiagramView.DestroyEditControl
        Debug.Print("fcDiagramView_DestroyEditControl")

        If CBool(Me.txtInPlaceEditor.Tag) = True Then
            Dim LoMMTableNode As ClsMMTableNode = CType(e.Node, ClsMMTableNode)
            Select Case e.Item.GetType.Name
                Case "ClsMMTableNode"
                    LoMMTableNode.Caption = Me.txtInPlaceEditor.Text
                    'LoTable.MMDSTableName = Me.txtTableCell.Text
                    LoMMTableNode.MMResizeAllToFitTable()
                Case "Cell"
                    Dim LoCell As TableNode.Cell = CType(e.Item, TableNode.Cell)
                    LoCell.Text = Me.txtInPlaceEditor.Text
                    LoMMTableNode.MMResizeAllToFitTable()
            End Select
            RefreshSelectedItemProperties(LoMMTableNode)
        End If
        'reset vaules for next use
        Me.txtInPlaceEditor.Tag = CBool("FALSE")
        Me.txtInPlaceEditor.Text = ""
        Me.txtInPlaceEditor.Visible = False
    End Sub
    'perform zooming or scrolling
    Private Sub fcDiagramView_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles fcDiagramView.MouseWheel
        Debug.Print("fcDiagramView_MouseWheel")

        If Control.ModifierKeys = Keys.Control Then
            'zooming
            ZoomToPoint(Cursor.Position, e.Delta)
        Else
            'vertical scrolling
            Zoom(0, IIf(e.Delta < 0, 20, -20)) 'or Zoom(0, -(e.Delta / Math.Abs(e.Delta) * 20))
            'this oddity (-(e.Delta / Math.Abs(e.Delta)) makes value for zooming with right sign (+ or -)
        End If
    End Sub
#End Region
#Region "MoHand - Events handler"
    'OnChanGePrimaryOperationOfHand
    Private Sub MoHand_OnChanGePrimaryOperationOfHand(ByVal OldStatus As ModBase.GePrimaryOperationOfHand) Handles MoHand.OnChangePrimaryOperationOfHand
        ManifestPrimaryOperationOfHandOnForm(OldStatus)
    End Sub
    'OnChanGeSecondaryOperationOfHand
    Private Sub MoHand_OnChanGeSecondaryOperationOfHand(ByVal OldStatus As ModBase.GeSecondaryOperationOfHand) Handles MoHand.OnChangeSecondaryOperationOfHand
        ManifestSecondaryOperationOfHandOnForm(OldStatus)
    End Sub
    'OnChangeTypeOfLink
    Private Sub MoHand_OnChangeTypeOfLink(ByVal OldTypeOfLink As kkRelationTypes) Handles MoHand.OnChangeTypeOfLink
        ManifestTypeOfLink(OldTypeOfLink)
    End Sub
#End Region
#Region "MoAmodFile - Events handler"
    Private Sub MoAmodFile_MMFileWasChangedToValue(ByVal Value As Boolean) Handles MoAmodFile.MMFileWasChangedToValue
        SetEnableMenu()
    End Sub
#End Region
#Region "txtInPlaceEditor - Events handler"
    'keypress on txtInPlaceEditor
    Private Sub txtInPlaceEditor_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtInPlaceEditor.KeyPress
        Debug.Print("txtInPlaceEditor_KeyPress")

        Select Case Asc(e.KeyChar)
            Case 13
                'ENTER = accept changes
                Me.txtInPlaceEditor.Tag = CBool("TRUE") 'saving value needed in DestroyEditControl sub
                Me.fcDiagramView.EndEdit(True) 'it doesnt matter on "accept" parameter because Im using my own DevExpress EditControl; http://mindfusion.eu/Forum/YaBB.pl?board=fcnet_disc;action=display;num=1208266554
            Case 27
                'ESC = reject changes
                Me.txtInPlaceEditor.Tag = CBool("FALSE") 'saving value needed in DestroyEditControl sub
                Me.fcDiagramView.EndEdit(False) 'it doesnt matter on "accept" parameter because Im using my own DevExpress EditControl; http://mindfusion.eu/Forum/YaBB.pl?board=fcnet_disc;action=display;num=1208266554
        End Select
    End Sub
    'lost focus on txtInPlaceEditor
    Private Sub txtInPlaceEditor_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtInPlaceEditor.LostFocus
        Debug.Print("txtInPlaceEditor_LostFocus")
        Me.fcDiagramView.EndEdit(True) 'it doesnt matter on "accept" parameter because Im using my own DevExpress EditControl; http://mindfusion.eu/Forum/YaBB.pl?board=fcnet_disc;action=display;num=1208266554
    End Sub
#End Region
#Region "UcnVisualPropertiesOfItemUC - Events handler"
    'accepting changes after editing visual  properties of item
    Private Sub UcnVisualPropertiesOfItemUC_MMValueChanged(ByVal TypeOfPropertyOfItem As UcnPropertiesOfItem.GeTypeOfPropertyOfItem, ByVal Value As Object) Handles UcnVisualPropertiesOfItemUC.MMValueChanged
        Debug.Print("UcnVisualPropertiesOfItemUC_ValueChanged")

        Dim LeResult As GeActionResult = GeActionResult.kkOk
        Dim LoItem As DiagramItem = Me.fcDiagram.ActiveItem

        If LoItem IsNot Nothing Then
            Select Case LoItem.GetType.Name
                ' '' ''Case "ClsMMTableNode"
                ' '' ''    Dim LoTable As ClsMMTableNode = CType(LoItem, ClsMMTableNode)
                ' '' ''    Select Case TypeOfPropertyOfItem
                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_GroupAppearanceSettings
                ' '' ''            'do nothing
                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_CaptionColor
                ' '' ''            LoTable.CaptionColor = CType(Value, Color)
                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_RowsColor
                ' '' ''            LoTable.TextColor = CType(Value, Color)
                ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkT_Brush
                ' '' ''            LoTable.Brush = CType(Value, LinearGradientBrush)
                ' '' ''        Case Else
                ' '' ''            LeResult =GeActionResult.kkError 
                ' '' ''            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMTableNode")
                ' '' ''    End Select
                ' '' ''    fcDiagram.Invalidate(LoTable.GetRepaintRect(False))

                Case "ClsMMLinkNode"
                    Dim LoLink As ClsMMLinkNode = CType(LoItem, ClsMMLinkNode)
                    Select Case TypeOfPropertyOfItem
                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkL_GroupAppearanceSettings
                            'do nothing
                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkL_CaptionColor
                            LoLink.TextColor = CType(Value, Color)
                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkL_Pen
                            Dim LoPen As Pen = CType(Value, Pen)
                            LoLink.Pen.Color = LoPen.Color
                            LoLink.Pen.Width = LoPen.Width
                        Case Else
                            LeResult = GeActionResult.kkError
                            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMLinkNode")
                    End Select
                    ' '' ''Case "ClsMMContainerNode"
                    ' '' ''    Dim LoContainer As ClsMMContainerNode = CType(LoItem, ClsMMContainerNode)
                    ' '' ''    Select Case TypeOfPropertyOfItem
                    ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_GroupAppearanceSettings
                    ' '' ''            'do nothing
                    ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_CaptionColor
                    ' '' ''            LoContainer.CaptionColor = CType(Value, Color)
                    ' '' ''        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_Brush
                    ' '' ''            LoContainer.Brush = CType(Value, LinearGradientBrush)
                    ' '' ''        Case Else
                    ' '' ''            LeResult =GeActionResult.kkError 
                    ' '' ''            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMContainerNode")
                    ' '' ''    End Select
                Case "ClsMMShapeNode"
                    Dim LoShapeNode As ClsMMShapeNode = CType(LoItem, ClsMMShapeNode)
                    Select Case TypeOfPropertyOfItem
                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkC_GroupAppearanceSettings
                            'do nothing
                        Case UcnPropertiesOfItem.GeTypeOfPropertyOfItem.kkS_Brush
                            LoShapeNode.Brush = CType(Value, LinearGradientBrush)
                        Case Else
                            LeResult = GeActionResult.kkError
                            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - ClsMMShapeNode")
                    End Select
                Case Else
                    LeResult = GeActionResult.kkError
                    Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - LoItem.GetType.Name")
            End Select
        Else
            LeResult = GeActionResult.kkError
            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_ValueChanged - LoItem = Nothing")
        End If

        If LeResult = GeActionResult.kkOk Then MoAmodFile.FileWasModified = True
    End Sub
#End Region
#Region "UcnPropertiesOfItemUC - Events handler"
    'accepting changes after editing properties of item
    Private Sub UcnPropertiesOfItemUC_MMValueChanged(ByVal Column As DevExpress.XtraGrid.Columns.GridColumn, ByVal NewValue As Object, ByVal OldValue As Object) Handles UcnPropertiesOfItemUC.MMValueChanged
        MoAmodFile.FileWasModified = True

        Try
            Select Case Column.Caption
                Case "Nazov unitu"
                    CType(Me.fcDiagram.ActiveItem, ClsMMContainerNode).Caption = CStr(NewValue)
                Case "Nazov tabulky"
                    CType(Me.fcDiagram.ActiveItem, ClsMMTableNode).Caption = CStr(NewValue)
                    MoAmodFile.Trigger_TablesUpdateTableNameAfterAppTableName(CStr(NewValue))
                    MoAmodFile.Trigger_HierarchyUpdateParentTableAfterAppTableName(NewValue, OldValue)
                Case "Support tabulka"
                    CType(Me.fcDiagram.ActiveItem, ClsMMTableNode).MMIsSupportTable = CBool(NewValue)
            End Select
        Catch ex As Exception
            Debug.Print("CHYBA!!! - UcnPropertiesOfItemUC_MMValueChanged")
        End Try
    End Sub
#End Region
#Region "UcnPropertiesOfTableRowsUC - Events handler"
    'accepting changes after editing properties of table rows
    Private Sub UcnPropertiesOfTableRowsUC_MMValueChanged(ByVal Column As DevExpress.XtraGrid.Columns.GridColumn, ByVal NewValue As Object, ByVal OldValue As Object) Handles UcnPropertiesOfTableRowsUC.MMValueChanged
        MoAmodFile.FileWasModified = True

        Try
            Select Case Column.Caption
                Case "Datovy nazov stlpca", "Datovy typ"
                    CType(Me.fcDiagram.ActiveItem, ClsMMTableNode).MMRebuildTable(MoAmodFile)
            End Select
        Catch ex As Exception
            Debug.Print("CHYBA!!! - UcnPropertiesOfTableRowsUC_MMValueChanged")
        End Try
    End Sub
    'adding row to table
    Private Sub UcnPropertiesOfTableRowsUC_MMAddItem(ByRef Item As DiagramItem, ByVal NewRowPosition As Integer, ByVal NewDataNavigatorPosition As Integer) Handles UcnPropertiesOfTableRowsUC.MMAddItem
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkAddColumnToTable)
        LoAction.SetData(Item, "TABLE")
        LoAction.SetData("Komponent", "ORIGINALCOLUMNNAME")
        LoAction.SetData(NewRowPosition, "POSITIONOFCOLUMN")
        If Execute(LoAction) = GeActionResult.kkOk Then
            RefreshSelectedItemProperties(Item, NewDataNavigatorPosition) 'MoAmodFile.GetNumberOfColumns(CType(Item, ClsMMTableNode).Caption) - 1)
        Else
            Debug.Print("CHYBA!!! - UcnPropertiesOfTableRowsUC_MMAddItem")
        End If
    End Sub
    'removing row from table
    Private Sub UcnPropertiesOfTableRowsUC_MMRemoveItem(ByRef Item As DiagramItem, ByVal ColumnName As String, ByVal NewDataNavigatorPosition As Integer) Handles UcnPropertiesOfTableRowsUC.MMRemoveItem
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkRemoveColumnFromTable)
        LoAction.SetData(Item, "TABLE")
        LoAction.SetData(ColumnName, "COLUMNNAME")
        If Execute(LoAction) = GeActionResult.kkOk Then
            RefreshSelectedItemProperties(Item, NewDataNavigatorPosition) 'MoAmodFile.GetNumberOfColumns(CType(Item, ClsMMTableNode).Caption) - 1)
        Else
            Debug.Print("CHYBA!!! - UcnPropertiesOfTableRowsUC_MMRemoveItem")
        End If
    End Sub
    'moving row up
    Private Sub UcnPropertiesOfTableRowsUC_MMMoveUp(ByRef Item As MindFusion.Diagramming.DiagramItem, ByVal ColumnName As String) Handles UcnPropertiesOfTableRowsUC.MMMoveUp
        Debug.Print("UcnPropertiesOfTableRowsUC_MMMoveUp")

        Dim LoAction As ClsAction = New ClsAction(GeAction.kkMoveUpColumnOfTable)
        LoAction.SetData(Item, "TABLE")
        LoAction.SetData(ColumnName, "COLUMNNAME")
        If Execute(LoAction) = GeActionResult.kkOk Then
            RefreshSelectedItemProperties(Item, LoAction.GetData("NEWPOSITIONAFTERCOLUMNMOVE"))
        Else
            Debug.Print("CHYBA!!! - UcnPropertiesOfTableRowsUC_MMMoveUp")
        End If
    End Sub
    'moving row down
    Private Sub UcnPropertiesOfTableRowsUC_MMMoveDown(ByRef Item As MindFusion.Diagramming.DiagramItem, ByVal ColumnName As String) Handles UcnPropertiesOfTableRowsUC.MMMoveDown
        Debug.Print("UcnPropertiesOfTableRowsUC_MMMoveDown")

        Dim LoAction As ClsAction = New ClsAction(GeAction.kkMoveDownColumnOfTable)
        LoAction.SetData(Item, "TABLE")
        LoAction.SetData(ColumnName, "COLUMNNAME")
        If Execute(LoAction) = GeActionResult.kkOk Then
            RefreshSelectedItemProperties(Item, LoAction.GetData("NEWPOSITIONAFTERCOLUMNMOVE"))
        Else
            Debug.Print("CHYBA!!! - UcnPropertiesOfTableRowsUC_MMMoveDown")
        End If
    End Sub
    'changing actual selected row
    Private Sub UcnPropertiesOfTableRowsUC_MMPositionOfNavigatorChanged(ByVal Position As Integer) Handles UcnPropertiesOfTableRowsUC.MMPositionOfNavigatorChanged
        If Me.fcDiagram.ActiveItem IsNot Nothing Then
            If Me.fcDiagram.ActiveItem.GetType.Name = "ClsMMTableNode" Then
                Dim LoMMTableNode As ClsMMTableNode = CType(Me.fcDiagram.ActiveItem, ClsMMTableNode)
                LoMMTableNode.HighlightedRow = Position
            End If
        End If
    End Sub
#End Region
#Region "UcnRTFeditorUC - Events handler"
    'text is changing 
    Private Sub UcnRTFeditorUC_MMTextChanging() Handles UcnRTFeditorUC.MMTextChanging
        Dim LoItem As DiagramItem = Me.fcDiagram.ActiveItem
        If LoItem IsNot Nothing Then
            Select Case LoItem.GetType.Name
                Case "ClsMMShapeNode"
                    Dim LoMMShapeNode As ClsMMShapeNode = CType(LoItem, ClsMMShapeNode)
                    LoMMShapeNode.Text = UcnRTFeditorUC.ResultActualPlainText
                    MoAmodFile.FileWasModified = True
            End Select
        End If
    End Sub
    'text changes were confirmed
    Private Sub UcnRTFeditorUC_MMValueChangesConfirmed(ByVal NewValue As String) Handles UcnRTFeditorUC.MMValueChangesConfirmed
        Dim LoItem As DiagramItem = Me.fcDiagram.ActiveItem
        If LoItem IsNot Nothing Then
            Select Case LoItem.GetType.Name
                Case "ClsMMContainerNode"
                    Dim LoMMContainerNode As ClsMMContainerNode = CType(LoItem, ClsMMContainerNode)
                    MoAmodFile.UpdateDescriptionOfUnit(LoMMContainerNode.Caption, UcnRTFeditorUC.ResultRTFText)
                Case "ClsMMTableNode"
                    Dim LoMMTableNode As ClsMMTableNode = CType(LoItem, ClsMMTableNode)
                    Dim LiColumnIndex As Integer = UcnPropertiesOfTableRowsUC.Position
                    If LiColumnIndex = -1 Then
                        'table is selected 
                        MoAmodFile.UpdateDescriptionOfTable(LoMMTableNode.Caption, UcnRTFeditorUC.ResultRTFText)
                    Else
                        'tables cell is selected 
                        Dim LoRows() As DataRow = MoAmodFile.GetColumnsOfTable(LoMMTableNode.Caption, "Position ASC")
                        LoRows(LiColumnIndex)("_a_Description") = UcnRTFeditorUC.ResultRTFText
                    End If
                Case "ClsMMShapeNode"
                    Dim LoMMShapeNode As ClsMMShapeNode = CType(LoItem, ClsMMShapeNode)
                    LoMMShapeNode.Text = UcnRTFeditorUC.ResultPlainText
                    'LoMMShapeNode.Text = "<color=#2E7DA5>" & "<b>" & "My Table" & "</b>" & "</color>" 'UcnRTFeditorUC.Result
                    'Dim r2h As New RTFtoHTML
                    'r2h.rtf = UcnRTFeditorUC.Result
                    'LoMMShapeNode.Text = r2h.html
                Case Else
                    Debug.Print("CHYBA!!! - UcnRTFeditorUC_ValueChangesConfirmed")
            End Select
        Else
            MoAmodFile.UpdateDescriptionOfActualVersion(UcnRTFeditorUC.ResultRTFText)
        End If
    End Sub
#End Region
#Region "Panels + buttons - Events handler"
    'perform actions after panel is closed
    Private Sub dpActions_ClosedPanel(ByVal sender As Object, ByVal e As DevExpress.XtraBars.Docking.DockPanelEventArgs) Handles dpActions.ClosedPanel
        barCheckItemPanelActions.Checked = False
    End Sub
    'perform actions after panel is closed
    Private Sub dpOverview_ClosedPanel(ByVal sender As Object, ByVal e As DevExpress.XtraBars.Docking.DockPanelEventArgs) Handles dpOverview.ClosedPanel
        barCheckItemPanelOverview.Checked = False
    End Sub
    'perform actions after panel is closed
    Private Sub dpProperties_ClosedPanel(ByVal sender As Object, ByVal e As DevExpress.XtraBars.Docking.DockPanelEventArgs) Handles dpProperties.ClosedPanel
        barCheckItemPanelProperties.Checked = False
    End Sub
    'perform actions after panel is closed
    Private Sub dpNotes_ClosedPanel(ByVal sender As Object, ByVal e As DevExpress.XtraBars.Docking.DockPanelEventArgs) Handles dpNotes.ClosedPanel
        barCheckItemPanelNotes.Checked = False
    End Sub
#End Region
#Region "ImageListBoxControls for panels - Events handler"
    'selecting new item, starting dragging item, reassigning primary operation
    Private Sub ilbActions_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ilbActions.MouseDown
        'accept only left mouse button
        If Control.MouseButtons = Windows.Forms.MouseButtons.Left Then
            'reassigning primary operation
            If Not MoHand.IsChangingPrimaryOperation Then MoHand.PrimaryOperation = ilbActions.SelectedIndex

            Dim LiItemUnderCursor As Integer = ilbActions.IndexFromPoint(New Point(e.X, e.Y))
            'accept only item, dont accept arrow tool (index is 0)
            If LiItemUnderCursor > 0 Then
                'select actual item
                ilbActions.SelectedIndex = LiItemUnderCursor
                'starting draging an item
                Dim LeTypeOfDragDropItem As GeTypeOfDragDropItem = GeTypeOfDragDropItem.kkNone
                Select Case LiItemUnderCursor
                    Case 1
                        LeTypeOfDragDropItem = GeTypeOfDragDropItem.kkTable
                    Case 2
                        LeTypeOfDragDropItem = GeTypeOfDragDropItem.kkContainer
                    Case 3
                        LeTypeOfDragDropItem = GeTypeOfDragDropItem.kkNote
                    Case Else
                        LeTypeOfDragDropItem = GeTypeOfDragDropItem.kkNone
                End Select
                DoDragDrop(New ClsDragDropItem(LeTypeOfDragDropItem), DragDropEffects.Copy)
            End If
        End If
    End Sub
    'canceling secondary operation
    Private Sub ilbRelationships_MouseDown(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles ilbRelationships.MouseDown
        'canceling secondary operation
        If Not MoHand.IsChangingSecondaryOperation Then MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkIdle
    End Sub
    'setting new type of link of hand
    Private Sub ilbRelationships_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ilbRelationships.SelectedIndexChanged
        'checking semaphore
        If Not MoHand.IsChangingTypeOfLink Then
            Select Case ilbRelationships.SelectedIndex
                Case 0
                    MoHand.TypeOfLink = kkRelationTypes.kk_1_01
                Case 1
                    MoHand.TypeOfLink = kkRelationTypes.kk_1_1
                Case 2
                    MoHand.TypeOfLink = kkRelationTypes.kk_1_1n
                Case 3
                    MoHand.TypeOfLink = kkRelationTypes.kk_1_n
                Case Else
                    Debug.Print("CHYBA!!! - ilbRelationships_SelectedIndexChanged")
            End Select
            'MoHand.TypeOfLink = ilbRelationships.SelectedIndex
            ' ''Select Case ilbRelationships.SelectedIndex
            ' ''    Case 0
            ' ''        MoHand.TypeOfLink = GeTypeOfLink.kkLink1a01
            ' ''    Case 1
            ' ''        MoHand.TypeOfLink = GeTypeOfLink.kkLink1a1N
            ' ''    Case 2
            ' ''        MoHand.TypeOfLink = GeTypeOfLink.kkLink1aN
            ' ''End Select
        End If
    End Sub
#End Region
#Region "Menu - Events handler"
    'new file
    Private Sub barBtnNew_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnNew.ItemClick
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkNewFile)
        Execute(LoAction)
    End Sub
    'opening file
    Private Sub barBtnOpen_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnOpen.ItemClick
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkOpenFile)
        Execute(LoAction)
    End Sub
    'saving file
    Private Sub barBtnSave_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnSave.ItemClick
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkSaveFile)
        Execute(LoAction)
    End Sub
    'closing file
    Private Sub barBtnClose_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnClose.ItemClick
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkCloseFile)
        Execute(LoAction)
    End Sub
    'exit application
    Private Sub barBtnExit_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnExit.ItemClick
        Me.Close()
    End Sub
    'exporting to xMod
    Private Sub barBtnExportXmod_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnExportXmod.ItemClick
        SaveFileDialog.InitialDirectory = MoApplicationFile.Path
        SaveFileDialog.Filter = "Subory xMod(*.xmod)|*.xmod"
        SaveFileDialog.Title = "Export do suboru xMod"
        SaveFileDialog.FileName = "Export"
        If SaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
            MoAmodFile.ExportToxMod(SaveFileDialog.FileName)
        End If
    End Sub

    'TODO
    'generate formulars
    Private Sub barBtnGenerateFormular_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnGenerateFormular.ItemClick
        Dim LoMMContainerNode As ClsMMContainerNode = CType(Me.fcDiagram.ActiveItem, ClsMMContainerNode)
        Dim nazovUnitu As String = LoMMContainerNode.Caption
        'TODO: nefunguje ziskanie nazvu modulu z diagramu (asi vtedy, ked sa klikne len pravym na modul). Treba najprv kliknut lavym a potom pravym
        'MessageBox.Show(nazovUnitu)

        Dim globalPath As String = System.IO.Path.GetDirectoryName(MoApplicationFile.Path)
        Dim templatesPath As String = System.IO.Path.Combine(globalPath, "Templates")
        Dim exportedFormsPath As String = System.IO.Path.Combine(globalPath, "VygenerovaneFormulare")

        'TODO: dsComponents musi byt nacitany pred generovanim formulara
        If MoAmodFile.Dat.DsComponents Is Nothing Then

            Dim pathDsComponents As String = System.IO.Path.Combine(templatesPath, "component_tpls.xml")
            MessageBox.Show("Nie je nacitany dataset komponentov! Skusim ho nacitat z " & vbCrLf & pathDsComponents)
            If MoAmodFile.Dat.LoadTemplateDs(pathDsComponents) = True Then
                MessageBox.Show("Uspesne nacitany z defaultneho nazvu suboru!")
            Else
                MessageBox.Show("Nenajdeny ani v defaultnom subore! Za chvilu padneeeeeeeeeem!")
            End If
        End If
        Dim aaa As DsAmod = MoAmodFile.Dat.DsAmod
        Dim frmFormulareExport As frmFormulareExport = New frmFormulareExport(templatesPath, exportedFormsPath, nazovUnitu, MoAmodFile.Dat)
        frmFormulareExport.Show()
    End Sub

    'creating template for table
    Private Sub BarBtnCreateTemplate_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barBtnCreateTemplate.ItemClick
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkCreateTemplate)
        Execute(LoAction)
    End Sub

    Private Sub barCheckItemPanelActions_CheckedChanged(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barCheckItemPanelActions.CheckedChanged
        If barCheckItemPanelActions.Checked Then
            dpActions.Show()
        Else
            dpActions.Hide()
        End If
    End Sub
    Private Sub barCheckItemPanelOverview_CheckedChanged(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barCheckItemPanelOverview.CheckedChanged
        If barCheckItemPanelOverview.Checked Then
            dpOverview.Show()
        Else
            dpOverview.Hide()
        End If
    End Sub
    Private Sub barCheckItemPanelProperties_CheckedChanged(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barCheckItemPanelProperties.CheckedChanged
        If barCheckItemPanelProperties.Checked Then
            dpProperties.Show()
        Else
            dpProperties.Hide()
        End If
    End Sub
    Private Sub barCheckItemPanelNotes_CheckedChanged(ByVal sender As Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles barCheckItemPanelNotes.CheckedChanged
        If barCheckItemPanelNotes.Checked Then
            dpNotes.Show()
        Else
            dpNotes.Hide()
        End If
    End Sub
#End Region
#End Region
#Region "Subs"
    'initializing application before apllication starts
    Private Sub InitializeApplication()
        Debug.Print("CESTA K SUBORU EXE: " & Application.ExecutablePath)
        Debug.Print("SUBOR EXE: " & IO.Path.GetFileName(Application.ExecutablePath))

        'setting paths
        Dim LsApplicationPath As String = Application.ExecutablePath
        Dim LsUserSettingsPath As String = IO.Path.Combine(IO.Path.GetDirectoryName(LsApplicationPath), "Data\UserSettings.xml")

        'opening application file
        MoApplicationFile = New ClsFileOfApplication(LsApplicationPath)

        'creating user settings file
        Try
            'creating path + file on disk
            If Not IO.File.Exists(LsUserSettingsPath) Then
                Dim LoDirectoryInfo As IO.DirectoryInfo
                LoDirectoryInfo = IO.Directory.CreateDirectory(IO.Path.GetDirectoryName(LsUserSettingsPath))
                Dim LoStreamWriter As IO.StreamWriter
                LoStreamWriter = IO.File.CreateText(LsUserSettingsPath)
            End If

            'opening file
            MoUserSettingsFile = New ClsUserSettings(LsUserSettingsPath)
            MoUserSettingsFile.OpenFile()
        Catch ex As Exception
            Debug.Print("CHYBA!!! - InitializeApplication")
        End Try
    End Sub
    'setting settings before apllication starts
    Private Sub SetSettingsBeforeApplicationStarts()
        Debug.Print("SetSettingsBeforeApplicationStarts")
        'load user settings from file
        LoadUserSettings()
        'clear diagram items, panels info, grid datasource,...
        ClearAllComponents()

        'setting diagram settings
        SetDiagramSettings()

        'setting dock panels settings - restoring settings
        SetDockPanelsSettings()

        '' ''create new file
        ' ''Dim LoAction As ClsAction = New ClsAction(GeAction.kkNewFile)
        ' ''If Execute(LoAction) <> GeActionResult.kkOk Then
        ' ''    'if creating a new file wasnt successful
        ' ''    'set enable/disable values for desktop (diagram and panels) and menu & toolbar.
        ' ''    'SetEnableAfterChangeOfStateOfFile() is called after successful creating a file
        ' ''    SetEnableAfterChangeOfStateOfFile()
        ' ''End If

        'settings panels, caption,... via closing imaginary file (now there shouldnt be any opened file)
        'SetEnableAfterChangeOfStateOfFile method is called after successful closing a file
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkCloseFile)
        If Execute(LoAction) <> GeActionResult.kkOk Then
            'if closing a file wasnt successful
            'set enable/disable values for desktop (diagram and panels) and menu & toolbar.
            SetEnableAfterChangeOfStateOfFile()
        End If
    End Sub
    'applying dock panels saved position
    Private Function ApplyDockPanelsSavedPosition() As GeActionResult
        Try
            'reading settings from DS
            Dim LsString As String = MoUserSettingsFile.GetDockPanelsPosition()
            'if something was loaded = if dock panels position was saved
            If LsString <> "" Then
                'create stream
                Dim LoStream As System.IO.Stream = New System.IO.MemoryStream()
                'create streamwriter
                Dim LoStreamWriter As IO.StreamWriter = New IO.StreamWriter(LoStream)
                'write string to stream
                LoStreamWriter.Write(LsString)
                'flush = Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream
                LoStreamWriter.Flush()
                'set the stream position to the beginning
                LoStream.Seek(0, System.IO.SeekOrigin.Begin)

                'restoring settings from stream
                xtrBarManager.RestoreLayoutFromStream(LoStream)
                Return GeActionResult.kkOk
            Else
                Throw New Exception
            End If

        Catch ex As Exception
            Debug.Print("CHYBA!!! - ApplyDockPanelsSavedPosition - loading dock panels position")
        End Try

        SetCheckItemPanels()
    End Function
    'saving dock panels position
    Private Sub SaveDockPanelsSavedPosition()
        Try
            'create stream
            Dim LoStream As System.IO.Stream = New System.IO.MemoryStream()
            'saving settings to stream
            xtrBarManager.SaveLayoutToStream(LoStream)
            'set the stream position to the beginning
            LoStream.Seek(0, System.IO.SeekOrigin.Begin)
            'create streamreader
            Dim LoStreamReader As IO.StreamReader = New IO.StreamReader(LoStream)
            'read string from stream
            Dim LsString As String = LoStreamReader.ReadToEnd()

            'writing settings to DS
            MoUserSettingsFile.UpdateDockPanelsPosition(LsString)
        Catch ex As Exception
            Debug.Print("CHYBA!!! - SaveDockPanelsSavedPosition - saving dock panels position")
        End Try
    End Sub
    'loading user settings from file
    Private Sub LoadUserSettings()

    End Sub
    'setting diagram settings before apllication starts
    Private Sub SetDiagramSettings()
        Debug.Print("SetDiagramSettings")

        'diagram general settings
        Me.fcDiagramView.CustomBehavior = New ClsCustomBehavior(Me.fcDiagramView)
        'set ZOrder order because of possibility of editing links inside of container
        Me.fcDiagram.HitTestPriority = HitTestPriority.ZOrder

        Me.fcDiagramView.AutoScroll = True 'whether auto scrolling of the document area is enabled when new items are added or existing items are being dragged outside the visible area
        Me.fcDiagramView.ModifierKeyActions.Alt = ModifierKeyAction.Pan 'specify the function of the ALT key
        Me.fcDiagramView.ModifierKeyActions.Control = ModifierKeyAction.Select 'specify the function of the CTRL key
        Me.fcDiagramView.ModifierKeyActions.Shift = ModifierKeyAction.OverrideBehavior 'specify the function of the SHIFT key
        Me.fcDiagramView.DelKeyAction = DelKeyAction.None 'what action should be performed when the user hits the Del key
        Me.fcDiagramView.AllowDrop = True 'allowing drag&drop
        Me.fcDiagramView.Behavior = Behavior.Custom  'DrawLinks 'how the component responds to actions performed by the user
        Me.fcDiagramView.AllowInplaceEdit = False 'whether in-place editing of the text of objects is enabled
        Me.fcDiagramView.InplaceEditAcceptOnEnter = True 'whether pressing the ENTER key should exit inplace-edit mode and accept changes made to text
        Me.fcDiagramView.InplaceEditCancelOnEsc = True 'whether pressing the ESC key should exit inplace-edit mode and reject changes made to text
        Me.fcDiagram.ActiveItemHandlesColor = Color.Blue 'the color of the adjustment handles of the active item
        Me.fcDiagram.SelectedItemHandlesColor = Color.Gray 'the color of the manipulation handles of selected objects
        Me.fcDiagram.AutoResize = AutoResize.RightAndDown  'whether the document area must be resized automatically so it fits the diagram contents each time an item is created, deleted or moved, either by end-users or by calling of methods
        Me.fcDiagram.SelectionOnTop = True 'whether selected items should be painted on top of other items
        Me.fcDiagram.BackBrush = New SolidBrush(Color.LightSteelBlue) 'New LinearGradientBrush(Color.LightSteelBlue, Color.White, 45)
        Me.fcDiagram.EnableStyledText = True 'the value is used to initialize the EnableStyledText property of new nodes
        Me.fcDiagram.ShowAnchors = ShowAnchors.Never 'when anchors points should be displayed
        Me.fcDiagram.SnapToAnchor = SnapToAnchor.OnCreateOrModify  'when link ends are snapped to nearest anchor points
        'USED WHILE CREATING NEW ITEMS IN DIAGRAM AND IN DATASET!
        Me.fcDiagram.TableCaption = GsStringNullValue 'default text for tables' captions
        Me.fcDiagram.LinkText = GsStringNullValue 'default text of links
        Me.fcDiagram.ContainerCaption = GsStringNullValue 'default value for the Caption property of containers
        'USED WHILE CREATING NEW ITEMS IN DIAGRAM AND IN DATASET!

        'Me.fcDiagram.AllowUnanchoredLinks = False  'links can be connected to nodes to which there aren't anchor points assigned
        'Me.fcDiagram.RoutingOptions.TriggerRerouting = RerouteLinks.WhileCreating Or RerouteLinks.WhenModified 'in what circumstances links must be rerouted automatically

        Me.KeyPreview = True
        Me.txtInPlaceEditor.Visible = False
        Me.txtInPlaceEditor.MinimumSize = New Size(40, 20) 'txtInPlaceEditor is used for in-place editing of cell, caption,...

        'link settings
        Me.fcDiagram.RoundedLinks = True 'rounded bends     

        'settings connected with diagram
        MoHand = New ClsHand
        MoHand.PrimaryOperation = GePrimaryOperationOfHand.kkNeutral
        MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkIdle
        MoHand.TypeOfLink = kkRelationTypes.kk_1_n

        RefreshSelectedItemProperties(Nothing)
        nbgVisualPropertiesOfItem.Visible = False
        nbgPropertiesOfItem.Visible = False
        nbgPropertiesOfTableRows.Visible = False
    End Sub
    'setting dock panels settings before apllication starts
    Private Sub SetDockPanelsSettings()
        Debug.Print("SetDockPanelsSettings")

        If ApplyDockPanelsSavedPosition() <> GeActionResult.kkOk Then
            Me.dpActions.Show()
            Me.dpActions.Dock = DevExpress.XtraBars.Docking.DockingStyle.Left
            Me.dpActions.Width = 150
            Me.dpActions.FloatSize = New System.Drawing.Size(150, 300)
            Me.barCheckItemPanelActions.Checked = True

            Me.dpOverview.Show()
            Me.dpOverview.Width = 300
            Me.dpOverview.FloatSize = New System.Drawing.Size(300, 300)
            Me.barCheckItemPanelOverview.Checked = True

            Me.dpProperties.Show()
            Me.dpProperties.Width = 300
            Me.dpProperties.FloatSize = New System.Drawing.Size(300, 300)
            Me.barCheckItemPanelProperties.Checked = True

            Me.dpNotes.Show()
            Me.dpNotes.Dock = DevExpress.XtraBars.Docking.DockingStyle.Bottom
            Me.dpNotes.Width = 150
            Me.dpNotes.FloatSize = New System.Drawing.Size(300, 150)
            Me.barCheckItemPanelNotes.Checked = True
        End If

        SetCheckItemPanels()

        Me.UcnNodesToolbarUC.Init(IO.Path.Combine(IO.Path.GetDirectoryName(MoApplicationFile.Path), "Data\NodeTemplates.xml"))
    End Sub
    'checks/unchecks barCheckItem menu items for dock panels
    Private Sub SetCheckItemPanels()
        barCheckItemPanelNotes.Checked = IIf(dpNotes.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible, True, False)
        barCheckItemPanelActions.Checked = IIf(dpActions.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible, True, False)
        barCheckItemPanelOverview.Checked = IIf(dpOverview.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible, True, False)
        barCheckItemPanelProperties.Checked = IIf(dpProperties.Visibility = DevExpress.XtraBars.Docking.DockVisibility.Visible, True, False)
    End Sub
    'saving user settings to file
    Private Sub SaveUserSettingsToFile()
        MoUserSettingsFile.SaveFile()
    End Sub
    'manifest primary operation of hand on form
    Private Sub ManifestPrimaryOperationOfHandOnForm(ByVal IeOldStatus As GePrimaryOperationOfHand)
        'set primary operation also to CustomBehavior object so it knows what to do when user is dragging mouse
        CType(Me.fcDiagramView.CustomBehavior, ClsCustomBehavior).CursorOperationOnDragging = MoHand.PrimaryOperation
        'if there is any secondary operation (ex. zoom) -> cancel it
        If MoHand.SecondaryOperation <> GeSecondaryOperationOfHand.kkIdle Then MoHand.SecondaryOperation = GeSecondaryOperationOfHand.kkIdle

        Me.fcDiagramView.ModificationStart = ModificationStart.AutoHandles
        Me.fcDiagramView.CustomNodeType = GetType(ClsMMTableNode)
        Me.fcDiagramView.Behavior = Behavior.Custom
        ilbActions.SelectedIndex = MoHand.PrimaryOperation
        ' ''Select Case MoHand.PrimaryOperation
        ' ''    Case GePrimaryOperationOfHand.kkNeutral
        ' ''        ilbActions.SelectedIndex = 0
        ' ''    Case GePrimaryOperationOfHand.kkTable
        ' ''        ilbActions.SelectedIndex = 1
        ' ''    Case GePrimaryOperationOfHand.kkContainer
        ' ''        ilbActions.SelectedIndex = 2
        ' ''End Select
    End Sub
    'manifest secondary operation of hand on form
    Private Sub ManifestSecondaryOperationOfHandOnForm(ByVal IeOldStatus As GeSecondaryOperationOfHand)
        'if there was zoom operation -> set back cursor
        If IeOldStatus = GeSecondaryOperationOfHand.kkZoom Then
            Me.fcDiagramView.PointerCursor = Cursors.Arrow
        End If

        Select Case MoHand.SecondaryOperation
            Case GeSecondaryOperationOfHand.kkIdle
                MoHand.PrimaryOperation = MoHand.PrimaryOperation
            Case GeSecondaryOperationOfHand.kkZoom
                Me.fcDiagramView.PointerCursor = New Cursor(Me.GetType(), "MagnGlassNORMAL.cur")
                Me.fcDiagramView.ModificationStart = ModificationStart.SelectedOnly
                Me.fcDiagramView.Behavior = Behavior.DrawShapes
        End Select
    End Sub
    'manifest type of link on form
    Private Sub ManifestTypeOfLink(ByVal IeOldTypeOfLink As kkRelationTypes)
        Select Case MoHand.TypeOfLink
            Case kkRelationTypes.kk_1_01
                ilbRelationships.SelectedIndex = 0
            Case kkRelationTypes.kk_1_1
                ilbRelationships.SelectedIndex = 1
            Case kkRelationTypes.kk_1_1n
                ilbRelationships.SelectedIndex = 2
            Case kkRelationTypes.kk_1_n
                ilbRelationships.SelectedIndex = 3
            Case Else
                Debug.Print("CHYBA!!! - ManifestTypeOfLink")
        End Select
        'ilbRelationships.SelectedIndex = MoHand.TypeOfLink
        ' ''Select Case MoHand.TypeOfLink
        ' ''    Case GeTypeOfLink.kkLink1a01
        ' ''        ilbRelationships.SelectedIndex = 0
        ' ''    Case GeTypeOfLink.kkLink1a1N
        ' ''        ilbRelationships.SelectedIndex = 1
        ' ''    Case GeTypeOfLink.kkLink1aN
        ' ''        ilbRelationships.SelectedIndex = 2
        ' ''End Select
    End Sub
    'zoomimng to point
    Private Sub ZoomToPoint(ByVal IoPoint As Point, ByVal IiZoomFactor As Integer)
        Dim LoPoint As Point = fcDiagramView.PointToClient(IoPoint)
        Dim LoOldCursorPosition As PointF = fcDiagramView.ClientToDoc(LoPoint)

        fcDiagramView.ZoomFactor += IiZoomFactor / 30.0F
        Dim LoNewCursorPosition As PointF = fcDiagramView.ClientToDoc(fcDiagramView.PointToClient(Cursor.Position))
        Dim LnDeltaX As Single = (LoOldCursorPosition.X - LoNewCursorPosition.X)
        Dim LnDeltaY As Single = (LoOldCursorPosition.Y - LoNewCursorPosition.Y)
        Zoom(LnDeltaX, LnDeltaY)
    End Sub
    'zooming
    Private Sub Zoom(ByVal InDeltaX As Single, ByVal InDeltaY As Single)
        fcDiagramView.ScrollTo(IIf(fcDiagramView.ScrollX + InDeltaX < 0, 0, fcDiagramView.ScrollX + InDeltaX), IIf(fcDiagramView.ScrollY + InDeltaY < 0, 0, fcDiagramView.ScrollY + InDeltaY))
    End Sub
    'refreshing properties of all parts of selected item (item, rows,...)
    Private Sub RefreshSelectedItemProperties(ByRef OoItem As DiagramItem, Optional ByVal IiSelectedRow As Integer = -1)
        Debug.Print("RefreshSelectedItemProperties")

        If OoItem IsNot Nothing Then
            Select Case OoItem.GetType.Name
                Case "ClsMMTableNode"
                    Me.nbgPropertiesOfItem.GroupClientHeight = 55
                    Me.nbgPropertiesOfItem.Expanded = True
                    Me.nbgPropertiesOfTableRows.GroupClientHeight = 330
                    Me.nbgPropertiesOfTableRows.Expanded = True

                    Dim LoRows() As DataRow
                    nbgVisualPropertiesOfItem.Visible = False
                    nbgPropertiesOfItem.Visible = True
                    nbgPropertiesOfTableRows.Visible = True

                    Dim LoMMTableNode As ClsMMTableNode = CType(OoItem, ClsMMTableNode)
                    'refresh properties of item
                    LoRows = MoAmodFile.GetTable(LoMMTableNode.Caption)
                    UcnPropertiesOfItemUC.Init(LoMMTableNode, LoRows, IIf(IiSelectedRow = -1, 0, IiSelectedRow))
                    'refresh properties of rows of item
                    LoRows = MoAmodFile.GetColumnsOfTable(LoMMTableNode.Caption, "Position ASC")
                    UcnPropertiesOfTableRowsUC.Init(LoMMTableNode, LoRows, IIf(IiSelectedRow = -1, 0, IiSelectedRow), True)

                    'refresh RTF note
                    'call UcnPropertiesOfRowsOfTableUC.Position after UcnPropertiesOfRowsOfTableUC.Init !
                    Dim LiColumnIndex As Integer = UcnPropertiesOfTableRowsUC.Position
                    If LiColumnIndex = -1 Then
                        'table is selected 
                        UcnRTFeditorUC.Init(MoAmodFile.GetDescriptionOfTable(LoMMTableNode.Caption))
                    Else
                        'tables cell is selected 
                        UcnRTFeditorUC.Init(LoRows(LiColumnIndex).Item("_a_Description"))
                    End If
                Case "ClsMMLinkNode"
                    Me.nbgVisualPropertiesOfItem.GroupClientHeight = 45
                    Me.nbgVisualPropertiesOfItem.Expanded = True

                    Me.nbgVisualPropertiesOfItem.Visible = True
                    nbgPropertiesOfItem.Visible = False
                    nbgPropertiesOfTableRows.Visible = False

                    'refresh visual properties of item
                    UcnVisualPropertiesOfItemUC.Init(OoItem)
                Case "ClsMMContainerNode"
                    Me.nbgPropertiesOfItem.GroupClientHeight = 40
                    Me.nbgPropertiesOfItem.Expanded = True

                    Me.nbgVisualPropertiesOfItem.Visible = False
                    nbgPropertiesOfItem.Visible = True
                    nbgPropertiesOfTableRows.Visible = False

                    Dim LoMMContainerNode As ClsMMContainerNode = CType(OoItem, ClsMMContainerNode)
                    Dim LoRows() As DataRow = MoAmodFile.GetUnit(LoMMContainerNode.Caption)

                    'refresh properties of item
                    UcnPropertiesOfItemUC.Init(LoMMContainerNode, LoRows, IIf(IiSelectedRow = -1, 0, IiSelectedRow))
                    'refresh RTF note
                    UcnRTFeditorUC.Init(MoAmodFile.GetDescriptionOfUnit(LoMMContainerNode.Caption))
                Case "ClsMMShapeNode"
                    Me.nbgVisualPropertiesOfItem.GroupClientHeight = 25
                    Me.nbgVisualPropertiesOfItem.Expanded = True

                    Me.nbgVisualPropertiesOfItem.Visible = True
                    nbgPropertiesOfItem.Visible = False
                    nbgPropertiesOfTableRows.Visible = False

                    Dim LoMMShapeNode As ClsMMShapeNode = CType(OoItem, ClsMMShapeNode)
                    'refresh visual properties of item
                    UcnVisualPropertiesOfItemUC.Init(OoItem)
                    'refresh RTF note
                    UcnRTFeditorUC.Init(LoMMShapeNode.Text)
            End Select
        Else
            'clearing because  of situations when this code is fired immediately after any node is deleted
            UcnVisualPropertiesOfItemUC.Clear()
            UcnPropertiesOfItemUC.Clear()
            UcnPropertiesOfTableRowsUC.Clear()
            UcnRTFeditorUC.Clear()

            Me.nbgPropertiesOfItem.GroupClientHeight = 55
            Me.nbgPropertiesOfItem.Expanded = True

            'nothing is selected
            nbgVisualPropertiesOfItem.Visible = False
            nbgPropertiesOfItem.Visible = True
            nbgPropertiesOfTableRows.Visible = False

            Dim LoRows() As DataRow = MoAmodFile.GetActualVersion
            UcnVisualPropertiesOfItemUC.Init(Nothing)
            UcnPropertiesOfItemUC.Init(Nothing, LoRows, -1)
            UcnPropertiesOfTableRowsUC.Init(Nothing, Nothing)
            UcnRTFeditorUC.Init(MoAmodFile.GetDescriptionOfActualVersion)
        End If
    End Sub
    'clear diagram items, panels info, grid datasource,...
    Private Sub ClearAllComponents()
        Me.fcDiagram.ClearAll()

        UcnVisualPropertiesOfItemUC.Clear()
        UcnPropertiesOfItemUC.Clear()
        UcnPropertiesOfTableRowsUC.Clear()
        UcnRTFeditorUC.Clear()
    End Sub
    'set enable/disable values for everything :-) and perform another actions (caption of form,...)
    Private Sub SetEnableAfterChangeOfStateOfFile()
        Dim LbFileOpened As Boolean = (MoAmodFile.StateOfFile = GeFileState.kkOpened) Or (MoAmodFile.StateOfFile = GeFileState.kkNewFile)
        'setting caption of form
        SetCaptionOfForm()
        'menu items
        SetEnableMenu()
        'desktop items (panels,...)
        SetEnableDesktop()
    End Sub
    'set caption of form
    Private Sub SetCaptionOfForm()
        Select Case MoAmodFile.StateOfFile
            Case GeFileState.kkNotInit
                Me.Text = "Editor"
            Case GeFileState.kkNewFile
                Me.Text = "Editor - [Novy subor]"
            Case GeFileState.kkReady
                Debug.Print("CHYBA!!! - SetEnableAfterChangeOfStateOfFile - Case GeFileState.kkReady")
            Case GeFileState.kkOpened
                Me.Text = "Editor - " & MoAmodFile.Path
            Case Else
                Debug.Print("CHYBA!!! - SetEnableAfterChangeOfStateOfFile")
        End Select
    End Sub
    'set enable/disable values for menu and toolbar
    Private Sub SetEnableMenu()
        Dim LbFileOpened As Boolean = (MoAmodFile.StateOfFile = GeFileState.kkOpened) Or (MoAmodFile.StateOfFile = GeFileState.kkNewFile)

        'open menu item
        barBtnOpen.Enabled = True
        'save menu item
        barBtnSave.Enabled = IIf(LbFileOpened, LbFileOpened And MoAmodFile.FileWasModified, False)
        'close menu item
        barBtnClose.Enabled = LbFileOpened
        'export menu item
        barBtnExportXmod.Enabled = LbFileOpened
        'panels menu item
        barSubItemPanels.Enabled = LbFileOpened
    End Sub
    'set enable/disable values for desktop (diagram and panels)
    Private Sub SetEnableDesktop()
        'IbFirstStartOfApplication - used when application is started first time. For ex. when is not desirable to save dock panels position
        Dim LbFileOpened As Boolean = (MoAmodFile.StateOfFile = GeFileState.kkOpened) Or (MoAmodFile.StateOfFile = GeFileState.kkNewFile)

        tlDesktopLayout.Visible = LbFileOpened

        If LbFileOpened Then
            ApplyDockPanelsSavedPosition()
            '' ''!!! dpNotes - panel with notes should be first because there are GotFocus and LostFocus events causing flashing effect
            ' ''If barCheckItemPanelNotes.Checked Then dpNotes.Show()
            ' ''If barCheckItemPanelActions.Checked Then dpActions.Show()
            ' ''If barCheckItemPanelOverview.Checked Then dpProperties.Show()
            ' ''If barCheckItemPanelProperties.Checked Then dpOverview.Show()
        Else
            SaveDockPanelsSavedPosition()
            '!!! dpNotes - panel with notes should be first because there are GotFocus and LostFocus events causing flashing effect
            dpNotes.Hide()
            dpActions.Hide()
            dpProperties.Hide()
            dpOverview.Hide()
        End If
    End Sub
    'show popup menu
    Private Sub ShowPopupMenu(ByVal IeTypeOfPopupMenu As GeTypeOfPopupMenu, ByVal IoPoint As Point)
        Select Case IeTypeOfPopupMenu
            Case GeTypeOfPopupMenu.kkNodeContext
                xtrPopupMenuNodeContext.ShowPopup(IoPoint)
            Case GeTypeOfPopupMenu.kkUnitContext
                xtrPopupMenuUnit.ShowPopup(IoPoint)
            Case Else
                Debug.Print("CHYBA!!! - ShowPopupMenu")
        End Select
    End Sub
#End Region
#Region "Functions"
    'performs actions before closing application
    'returns value - true = application can be closed otherwise false
    Private Function CanExitApplication() As Boolean
        Dim LoAction As ClsAction = New ClsAction(GeAction.kkCloseFile)
        Return Execute(LoAction) = GeActionResult.kkOk
    End Function
    'returns created new node
    Private Function CreateNewNode(ByVal IeTypeOfNode As GePrimaryOperationOfHand) As DiagramNode
        Select Case IeTypeOfNode
            Case GePrimaryOperationOfHand.kkNeutral
                Debug.Print("CHYBA!!! - GetNewNode - Select Case IePrimaryOperationOfHand")
                Return Nothing
            Case GePrimaryOperationOfHand.kkTable
                Return New ClsMMTableNode(Me.fcDiagram)
            Case GePrimaryOperationOfHand.kkContainer
                Return New ClsMMContainerNode(Me.fcDiagram)
            Case GePrimaryOperationOfHand.kkNote
                Return New ClsMMShapeNode(Me.fcDiagram)
            Case Else
                Debug.Print("CHYBA!!! - GetNewNode")
                Return Nothing
        End Select
    End Function
    'returns if anchorpoint is free for accepting a new link
    Private Function IsFreeAnchorPoint(ByVal IoNode As DiagramNode, ByVal IoLink As DiagramLink, ByVal IoAnchorIndex As Integer, ByVal IiMaxNumberOfLinks As Integer) As Boolean
        Dim LoLink As DiagramLink
        Dim LiI, LiActualNumberOfLinks As Integer
        Dim LbOk As Boolean

        If IoLink IsNot Nothing Then
            LiActualNumberOfLinks = 0
            'checking IncomingLinks
            LiI = 0
            LbOk = True
            LoLink = IoNode.IncomingLinks.GetAt(LiI)
            While (LoLink IsNot Nothing) And (LbOk)
                If Not IoLink.DestinationAnchor.Equals(LoLink.DestinationAnchor) Then 'prevention of selfchecking of link
                    If LoLink.DestinationAnchor = IoAnchorIndex Then
                        LiActualNumberOfLinks += 1
                        If LiActualNumberOfLinks >= IiMaxNumberOfLinks Then LbOk = False
                    End If
                End If
                LiI += 1
                LoLink = IoNode.IncomingLinks.GetAt(LiI)
            End While

            'checking OutgoingLinks
            If LiActualNumberOfLinks < IiMaxNumberOfLinks Then
                LiI = 0
                LbOk = True
                LoLink = IoNode.OutgoingLinks.GetAt(LiI)
                While (LoLink IsNot Nothing) And (LbOk)
                    If Not IoLink.OriginAnchor.Equals(LoLink.OriginAnchor) Then 'prevention of selfchecking of link
                        If LoLink.OriginAnchor = IoAnchorIndex Then
                            LiActualNumberOfLinks += 1
                            If LiActualNumberOfLinks >= IiMaxNumberOfLinks Then LbOk = False
                        End If
                    End If
                    LiI += 1
                    LoLink = IoNode.OutgoingLinks.GetAt(LiI)
                End While
            End If
        End If

        Return LiActualNumberOfLinks < IiMaxNumberOfLinks
    End Function
    'checking rules for creation/modification of new link
    Private Function CheckLinkRules(ByVal IiMMLinkNode As ClsMMLinkNode, ByVal IoNode As DiagramNode, ByVal IoOrigin As DiagramNode, ByVal IoDestination As DiagramNode, ByVal IbModifying As Boolean) As Boolean
        Dim LbOk As Boolean = True

        'prevention of creation of link on the same node 
        LbOk = IIf(IoDestination.Equals(IoOrigin), False, True)

        'checking rules for creating of link
        If LbOk = True Then
            Select Case IiMMLinkNode.MMTypeOfLink
                Case GeTypeOfLink.kkRelationship
                    'accepting only table for creating a link
                    If (IoNode.GetType.Name = "ClsMMTableNode") Then
                        Dim LoMMTableNode As ClsMMTableNode = CType(IoNode, ClsMMTableNode)

                        If LoMMTableNode.MMGetNumberOfRelationshipsLinks(True) > 0 Then
                            'prevention of multiple parent in DS hierarchy
                            LbOk = False
                        Else
                            'prevention of cycle between nodes
                            LbOk = Not IsPathBetweenNodes(IoOrigin, IoDestination, GeTypeOfLink.kkRelationship)
                        End If
                    Else
                        LbOk = False
                    End If

                Case GeTypeOfLink.kkNote
                    If IbModifying Then
                        'prevention of deconnecting link from note shape while modifying
                        LbOk = IIf(IoDestination.GetType.Name <> "ClsMMShapeNode" And IoOrigin.GetType.Name <> "ClsMMShapeNode", False, True)
                        'prevenion of creating more connection between same nodes
                        If LbOk Then
                            LbOk = Not IsPathBetweenNodes(IoOrigin, IoDestination, GeTypeOfLink.kkNote)
                        End If
                    Else
                        LbOk = Not IsPathBetweenNodes(IoOrigin, IoDestination, GeTypeOfLink.kkNote)
                    End If
            End Select
        Else
            Debug.Print("CHYBA!!! - CheckLinkRules - IoDestination.Equals(IoOrigin)")
        End If

        Return LbOk
    End Function
    'examine possibility to drop node to container
    Private Function AllowDropNodeToContainer(ByVal LoCoordinate As PointF) As ClsMMContainerNode
        Dim LoNodesUnderCursor As DiagramNodeCollection = Me.fcDiagram.GetNodesAt(LoCoordinate)
        Dim LoMMContainerResult As ClsMMContainerNode = Nothing

        For Each LoNode As DiagramNode In LoNodesUnderCursor
            Select Case LoNode.GetType.Name
                Case "ClsMMContainerNode"
                    LoMMContainerResult = CType(LoNode, ClsMMContainerNode)
                    Exit For
            End Select
        Next

        Return LoMMContainerResult

        ' ''Dim LoNodeUnderCursor As DiagramNode = Me.fcDiagram.GetNodeAt(LoCoordinate)
        ' ''If LoNodeUnderCursor IsNot Nothing Then
        ' ''    If LoNodeUnderCursor.GetType.Name = "ClsMMContainerNode" Then
        ' ''        Return CType(LoNodeUnderCursor, ClsMMContainerNode)
        ' ''    Else
        ' ''        Return Nothing
        ' ''    End If
        ' ''Else
        ' ''    Return Nothing
        ' ''End If
    End Function
    'examine possibility to drop node outside of container
    Private Function AllowDropNodeOutsideOfContainer(ByVal LoCoordinate As PointF) As ClsMMContainerNode
        Dim LoNodesUnderCursor As DiagramNodeCollection = Me.fcDiagram.GetNodesAt(LoCoordinate)
        Dim LoMMContainerResult As ClsMMContainerNode = Nothing

        For Each LoNode As DiagramNode In LoNodesUnderCursor
            Select Case LoNode.GetType.Name
                Case "ClsMMContainerNode"
                    LoMMContainerResult = CType(LoNode, ClsMMContainerNode)
                    Exit For
            End Select
        Next

        Return LoMMContainerResult
    End Function
    'finds out if there is already connection between 2 nodes consist of specified type of links
    Private Function IsPathBetweenNodes(ByVal IoStartingNode As DiagramNode, ByVal IoEndingNode As DiagramNode, ByVal IeTypeOfLinks As GeTypeOfLink) As Boolean
        Dim LoPathFinder As New PathFinder(Me.fcDiagram, True)
        Dim LoPath As Path = LoPathFinder.FindShortestPath(IoStartingNode, IoEndingNode)
        Dim LbResult As Boolean = True

        If LoPath IsNot Nothing Then
            Select Case IeTypeOfLinks
                Case GeTypeOfLink.kkRelationship
                    'checking path consist of relationship links
                    For Each LoLink In LoPath.Links
                        Select Case LoLink.GetType.Name
                            Case "ClsMMLinkNode"
                                Select Case CType(LoLink, ClsMMLinkNode).MMTypeOfLink
                                    Case GeTypeOfLink.kkNote
                                        LbResult = False
                                        Exit For
                                End Select
                            Case Else
                                Debug.Print("CHYBA!!! - IsPathBetweenNodes - IeTypeOfLinks=kkRelationship - Select Case LoLink.GetType.Name")
                        End Select
                    Next
                Case GeTypeOfLink.kkNote
                    'checking path length 1 consist of note links = if theres direct connection between 2 nodes (e.g. connection length 1)
                    If LoPath.Length = 1 Then
                        Dim LoLink As DiagramLink = LoPath.Links(0)
                        Select Case LoLink.GetType.Name
                            Case "ClsMMLinkNode"
                                If CType(LoLink, ClsMMLinkNode).MMTypeOfLink = GeTypeOfLink.kkNote Then
                                    LbResult = True
                                Else
                                    LbResult = False
                                End If
                            Case Else
                                Debug.Print("CHYBA!!! - IsPathBetweenNodes - IeTypeOfLinks=kkNote - Select Case LoPath.Items(0).GetType.Name")
                        End Select
                    Else
                        LbResult = False
                    End If
            End Select
        Else
            LbResult = False
        End If

        Return LbResult
    End Function

    '#######################################
    'execute function - heart of application
    Public Function Execute(ByRef OoAction As ClsAction) As GeActionResult
        Dim LeResult As GeActionResult = GeActionResult.kkOk
        '---------------------------------------------
        'ACTION BEFORE ACTION
        '---------------------------------------------


        '---------------------------------------------
        'ACTION
        '---------------------------------------------
        Select Case OoAction.Action
            Case GeAction.kkNewFile
                'checking if any file is opened
                Select Case MoAmodFile.StateOfFile
                    Case GeFileState.kkNewFile, GeFileState.kkOpened
                        'close file
                        OoAction.Action = GeAction.kkCloseFile
                        LeResult = Execute(OoAction)
                        OoAction.Action = GeAction.kkNewFile
                    Case GeFileState.kkNotInit, GeFileState.kkReady
                        'nothing to close
                    Case Else
                        Debug.Print("CHYBA!!! - Execute - ACTION - kkNewFile")
                        LeResult = GeActionResult.kkError
                End Select

                If LeResult = GeActionResult.kkOk Then
                    'clear diagram - all groups, links and nodes in the diagram
                    ClearAllComponents()
                    LeResult = MoAmodFile.CreateNewFile
                End If

            Case GeAction.kkOpenFile
                Try
                    OpenFileDialog.InitialDirectory = MoApplicationFile.Path
                    OpenFileDialog.Filter = "Subory aMod(*.amod)|*.amod"
                    OpenFileDialog.Title = "Otvorit subor aMod"
                    If OpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
                        'closing file
                        OoAction.Action = GeAction.kkCloseFile
                        LeResult = Execute(OoAction)
                        OoAction.Action = GeAction.kkOpenFile

                        If LeResult = GeActionResult.kkOk Then
                            LeResult = MoAmodFile.Init(OpenFileDialog.FileName)
                            If LeResult = GeActionResult.kkOk Then
                                'file was opened successfully
                                LeResult = MoAmodFile.OpenFile
                                If LeResult = GeActionResult.kkOk Then
                                    'load diagram to FC
                                    Me.fcDiagram.LoadFromString(MoAmodFile.GetActualDiagramData)
                                Else
                                    LeResult = GeActionResult.kkError
                                End If
                            Else
                                LeResult = GeActionResult.kkError
                            End If
                        End If
                    Else
                        LeResult = GeActionResult.kkCancel
                    End If

                Catch ex As Exception
                    LeResult = GeActionResult.kkError
                End Try

            Case GeAction.kkSaveFile
                Try
                    Select Case MoAmodFile.StateOfFile
                        Case GeFileState.kkNewFile
                            SaveFileDialog.InitialDirectory = MoApplicationFile.Path
                            SaveFileDialog.Filter = "Subory aMod(*.amod)|*.amod"
                            SaveFileDialog.Title = "Ulozit subor aMod"
                            If SaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
                                LeResult = MoAmodFile.InitAfterNewFile(SaveFileDialog.FileName)
                            Else
                                LeResult = GeActionResult.kkCancel
                            End If
                        Case GeFileState.kkOpened
                            'do nothing
                            LeResult = GeActionResult.kkOk
                        Case Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkSaveFile")
                            LeResult = GeActionResult.kkError
                    End Select
                Catch ex As Exception
                    'probably error while SaveDialog was opened
                    LeResult = GeActionResult.kkError
                End Try
                If LeResult = GeActionResult.kkOk Then
                    LeResult = MoAmodFile.UpdateDiagramData(Me.fcDiagram.SaveToString(SaveToStringFormat.Xml, True))
                    If LeResult = GeActionResult.kkOk Then
                        MoAmodFile.SaveFile()
                    End If
                End If

            Case GeAction.kkCloseFile
                Select Case MoAmodFile.StateOfFile
                    Case GeFileState.kkNewFile, GeFileState.kkOpened
                        If MoAmodFile.FileWasModified Then
                            Select Case MessageBox.Show("Ulozit vykonane zmeny?", "Ulozenie zmien", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question)
                                Case DialogResult.Yes
                                    OoAction.Action = GeAction.kkSaveFile
                                    LeResult = Execute(OoAction)
                                    OoAction.Action = GeAction.kkCloseFile
                                Case DialogResult.No
                                    LeResult = GeActionResult.kkOk
                                Case DialogResult.Cancel
                                    LeResult = GeActionResult.kkCancel
                            End Select
                        End If

                        If LeResult = GeActionResult.kkOk Then
                            'clear diagram - all groups, links and nodes in the diagram
                            ClearAllComponents()
                            LeResult = MoAmodFile.CloseFile
                        End If
                    Case GeFileState.kkNotInit, GeFileState.kkReady
                        'nothing to close
                        LeResult = GeActionResult.kkOk
                    Case Else
                        Debug.Print("CHYBA!!! - Execute - ACTION - kkCloseFile")
                        LeResult = GeActionResult.kkError
                End Select

            Case GeAction.kkDeleteDiagramSelection
                Dim LoTableCollection As Collection = New Collection
                Dim LoContainerCollection As Collection = New Collection
                Dim LoShapeCollection As Collection = New Collection
                Dim LoRelationshipLinkCollection As Collection = New Collection
                Dim LoNoteLinkCollection As Collection = New Collection

                'filling collections of nodes in selection
                For Each LoNode As DiagramNode In fcDiagram.Selection.Nodes
                    Select Case LoNode.GetType.Name
                        Case "ClsMMTableNode"
                            LoTableCollection.Add(LoNode)
                        Case "ClsMMContainerNode"
                            LoContainerCollection.Add(LoNode)
                        Case "ClsMMShapeNode"
                            LoShapeCollection.Add(LoNode)
                        Case Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkDeleteDiagramSelection -   Select Case LoNode.GetType.Name")
                    End Select
                Next
                'filling collections of links in selection
                For Each LoLink As DiagramLink In fcDiagram.Selection.Links
                    Dim LoMMLinkNode As ClsMMLinkNode = CType(LoLink, ClsMMLinkNode)
                    Select Case LoMMLinkNode.MMTypeOfLink
                        Case GeTypeOfLink.kkRelationship
                            LoRelationshipLinkCollection.Add(LoLink)
                        Case GeTypeOfLink.kkNote
                            LoNoteLinkCollection.Add(LoLink)
                        Case Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkDeleteDiagramSelection -  Select Case LoMMLinkNode.MMTypeOfLink")
                    End Select
                Next

                'removing note links
                For Each LoLink As DiagramLink In LoNoteLinkCollection
                    OoAction.Action = GeAction.kkRemoveLinkFromDiagram
                    OoAction.SetData(LoLink, "LINK")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkDeleteDiagramSelection

                'removing relationship links
                For Each LoLink As DiagramLink In LoRelationshipLinkCollection
                    OoAction.Action = GeAction.kkRemoveLinkFromDiagram
                    OoAction.SetData(LoLink, "LINK")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkDeleteDiagramSelection

                'removing notes
                For Each LoNode As DiagramNode In LoShapeCollection
                    OoAction.Action = GeAction.kkRemoveShapeNodeFromDiagram
                    OoAction.SetData(LoNode, "NODE")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkDeleteDiagramSelection

                'removing tables
                For Each LoNode As DiagramNode In LoTableCollection
                    OoAction.Action = GeAction.kkRemoveTableFromDiagram
                    OoAction.SetData(LoNode, "NODE")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkDeleteDiagramSelection

                'removing containers
                For Each LoNode As DiagramNode In LoContainerCollection
                    OoAction.Action = GeAction.kkRemoveContainerFromDiagram
                    OoAction.SetData(LoNode, "NODE")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkDeleteDiagramSelection

            Case GeAction.kkAddItemToDiagram
                Dim LoNode As DiagramItem = OoAction.GetData("ITEM")
                Dim LsTypeOfNode As String = LoNode.GetType.Name
                Select Case LsTypeOfNode
                    Case "ClsMMContainerNode"
                        Dim LoMMContainerNode As ClsMMContainerNode = CType(LoNode, ClsMMContainerNode)
                        OoAction.Action = GeAction.kkAddContainerToDiagram
                        OoAction.SetData(LoMMContainerNode, "CONTAINER")
                        LeResult = Execute(OoAction)
                        OoAction.Action = GeAction.kkAddItemToDiagram
                    Case "ClsMMTableNode"
                        Dim LoMMTableNode As ClsMMTableNode = CType(LoNode, ClsMMTableNode)
                        OoAction.Action = GeAction.kkAddTableToDiagram
                        OoAction.SetData(LoMMTableNode, "TABLE")
                        LeResult = Execute(OoAction)
                        OoAction.Action = GeAction.kkAddItemToDiagram
                    Case "ClsMMShapeNode"
                        Dim LoMMShapeNode As ClsMMShapeNode = CType(LoNode, ClsMMShapeNode)
                        OoAction.Action = GeAction.kkAddShapeNodeToDiagram
                        OoAction.SetData(LoMMShapeNode, "SHAPENODE")
                        LeResult = Execute(OoAction)
                        OoAction.Action = GeAction.kkAddItemToDiagram
                    Case Else
                        Debug.Print("CHYBA!!! - Execute - ACTION - kkItemAddedToDiagram")
                        LeResult = GeActionResult.kkError
                End Select

            Case GeAction.kkAddTableToDiagram
                Dim LsNewAppTableName As String = ""
                Dim LoMMTableNode As ClsMMTableNode = OoAction.GetData("TABLE")
                Dim LoMMContainerNode As ClsMMContainerNode = OoAction.GetData("CONTAINER")
                LeResult = MoAmodFile.InsertNewTable(OoAction.GetData("ORIGINALAPPTABLENAME"), LoMMContainerNode.Caption, LsNewAppTableName)
                If LeResult = GeActionResult.kkOk Then
                    'table was successfully added
                    LoMMTableNode.Caption = LsNewAppTableName
                    'add table to diagram
                    Me.fcDiagram.Nodes.Add(LoMMTableNode)
                    'add table to container
                    LoMMContainerNode.MMAddNodeToContainerProgrammatically(LoMMTableNode)
                End If

            Case GeAction.kkAddColumnToTable
                Dim LoMMTableNode As ClsMMTableNode = OoAction.GetData("TABLE")
                Dim LsTableName As String = LoMMTableNode.Caption
                Dim LsOriginalColumnName As String = OoAction.GetData("ORIGINALCOLUMNNAME")
                Dim LsNewColumnName As String = ""
                Dim LiPositionOfColumn As Integer = OoAction.GetData("POSITIONOFCOLUMN")
                LeResult = MoAmodFile.InsertNewColumn(LsTableName, LsOriginalColumnName, LsNewColumnName, LiPositionOfColumn)
                'resize table in all cases (LeResult = whatever)
                LoMMTableNode.MMRebuildTable(MoAmodFile)

            Case GeAction.kkAddContainerToDiagram
                Dim LsNewContainerName As String = ""
                Dim LoMMContainerNode As ClsMMContainerNode = OoAction.GetData("CONTAINER")

                LeResult = MoAmodFile.InsertNewUnit(OoAction.GetData("ORIGINALCONTAINERNAME"), LsNewContainerName)
                If LeResult = GeActionResult.kkOk Then
                    'container was successfully added
                    LoMMContainerNode.Caption = LsNewContainerName
                    'add container to diagram
                    Me.fcDiagram.Nodes.Add(LoMMContainerNode)
                    'add central table
                    Dim LoMMTableNode As ClsMMTableNode = New ClsMMTableNode(Me.fcDiagram)
                    'resize container size
                    LoMMContainerNode.MMResizeAllToFitContainer()
                    'set position of table in container
                    LoMMTableNode.Bounds = New RectangleF(LoMMContainerNode.Bounds.X + LoMMContainerNode.Margin, LoMMContainerNode.Bounds.Y + LoMMContainerNode.Margin + LoMMContainerNode.CaptionHeight, LoMMTableNode.Bounds.Width, LoMMTableNode.Bounds.Height)

                    OoAction.Action = GeAction.kkAddTableToDiagram
                    OoAction.SetData(LoMMTableNode, "TABLE")
                    LeResult = Execute(OoAction)
                    OoAction.Action = GeAction.kkAddContainerToDiagram
                    If LeResult = GeActionResult.kkOk Then
                        'table was successfully added
                        'add table to hierarchy
                        OoAction.Action = GeAction.kkAddTableToHierarchy
                        OoAction.SetData(LoMMTableNode.Caption, "NAMEOFTABLEFORHIERARCHY")
                        LeResult = Execute(OoAction)
                        OoAction.Action = GeAction.kkAddContainerToDiagram
                    End If
                End If

            Case GeAction.kkAddShapeNodeToDiagram
                Dim LoMMShapeNode As ClsMMShapeNode = OoAction.GetData("SHAPENODE")
                'add ShapeNodeto diagram
                Me.fcDiagram.Nodes.Add(LoMMShapeNode)
                MoAmodFile.FileWasModified = True

            Case GeAction.kkAddTableToHierarchy
                LeResult = MoAmodFile.InsertNewTableToHierarchy(OoAction.GetData("NAMEOFTABLEFORHIERARCHY"))

            Case GeAction.kkAddLinkToDiagram
                Dim LoLink As ClsMMLinkNode = OoAction.GetData("LINK")
                LeResult = MoAmodFile.InsertNewRelationshipToHierarchy(CType(LoLink.Origin, ClsMMTableNode).Caption, CType(LoLink.Destination, ClsMMTableNode).Caption, LoLink.MMRelationType)

            Case GeAction.kkMoveUpColumnOfTable
                Dim LoMMTableNode As ClsMMTableNode = OoAction.GetData("TABLE")
                Dim LiNewColumnPosition As Integer = -1 'zero based position for datanavigator
                LeResult = MoAmodFile.UpdateUpColumnPosition(LoMMTableNode.Caption, OoAction.GetData("COLUMNNAME"), LiNewColumnPosition)
                OoAction.SetData(LiNewColumnPosition - 1, "NEWPOSITIONAFTERCOLUMNMOVE")
                LoMMTableNode.MMRebuildTable(MoAmodFile)

            Case GeAction.kkMoveDownColumnOfTable
                Dim LoMMTableNode As ClsMMTableNode = OoAction.GetData("TABLE")
                Dim LiNewColumnPosition As Integer = -1 'zero based position for datanavigator
                LeResult = MoAmodFile.UpdateDownColumnPosition(LoMMTableNode.Caption, OoAction.GetData("COLUMNNAME"), LiNewColumnPosition)
                OoAction.SetData(LiNewColumnPosition - 1, "NEWPOSITIONAFTERCOLUMNMOVE")
                LoMMTableNode.MMRebuildTable(MoAmodFile)

            Case GeAction.kkRemoveColumnFromTable
                Dim LoMMTableNode As ClsMMTableNode = OoAction.GetData("TABLE")
                Dim LsColumnName As String = LoMMTableNode.Caption
                LeResult = MoAmodFile.DeleteColumn(LoMMTableNode.Caption, OoAction.GetData("COLUMNNAME"))
                LoMMTableNode.MMRebuildTable(MoAmodFile)

            Case GeAction.kkRemoveLinkFromDiagram
                Dim LoMMLinkNode As ClsMMLinkNode = OoAction.GetData("LINK")
                Select Case LoMMLinkNode.MMTypeOfLink
                    Case GeTypeOfLink.kkRelationship
                        LeResult = MoAmodFile.DeleteRelationShipFromHierarchy(CType(LoMMLinkNode.Origin, ClsMMTableNode).Caption, CType(LoMMLinkNode.Destination, ClsMMTableNode).Caption)
                        If LeResult = GeActionResult.kkOk Then
                            Me.fcDiagram.Links.Remove(LoMMLinkNode)
                        End If
                    Case GeTypeOfLink.kkNote
                        Me.fcDiagram.Links.Remove(LoMMLinkNode)
                    Case Else
                        Debug.Print("CHYBA!!! - Execute - ACTION - kkRemoveLinkFromDiagram")
                End Select

            Case GeAction.kkRemoveShapeNodeFromDiagram
                Dim LoMMShapeNode As ClsMMShapeNode = OoAction.GetData("NODE")
                Dim LoNoteLinkCollection As Collection = New Collection

                For Each LoLink As DiagramLink In LoMMShapeNode.GetAllLinks
                    Dim LoMMLinkNode As ClsMMLinkNode = CType(LoLink, ClsMMLinkNode)
                    Select Case LoMMLinkNode.MMTypeOfLink
                        Case GeTypeOfLink.kkNote
                            LoNoteLinkCollection.Add(LoLink)
                        Case Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkRemoveShapeNodeFromDiagram - GetAllLinks")
                    End Select
                Next

                'removing note links
                For Each LoLink As DiagramLink In LoNoteLinkCollection
                    OoAction.Action = GeAction.kkRemoveLinkFromDiagram
                    OoAction.SetData(LoLink, "LINK")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkRemoveShapeNodeFromDiagram

                Me.fcDiagram.Nodes.Remove(LoMMShapeNode)

            Case GeAction.kkRemoveTableFromDiagram
                Dim LoMMTableNode As ClsMMTableNode = OoAction.GetData("NODE")
                Dim LoRelationshipLinkCollection As Collection = New Collection
                Dim LoNoteLinkCollection As Collection = New Collection

                For Each LoLink As DiagramLink In LoMMTableNode.GetAllLinks
                    Dim LoMMLinkNode As ClsMMLinkNode = CType(LoLink, ClsMMLinkNode)
                    Select Case LoMMLinkNode.MMTypeOfLink
                        Case GeTypeOfLink.kkRelationship
                            LoRelationshipLinkCollection.Add(LoLink)
                        Case GeTypeOfLink.kkNote
                            LoNoteLinkCollection.Add(LoLink)
                        Case Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkRemoveTableFromDiagram - GetAllLinks")
                    End Select
                Next

                'removing relationship links
                For Each LoLink As DiagramLink In LoRelationshipLinkCollection
                    OoAction.Action = GeAction.kkRemoveLinkFromDiagram
                    OoAction.SetData(LoLink, "LINK")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkRemoveTableFromDiagram

                'removing note links
                For Each LoLink As DiagramLink In LoNoteLinkCollection
                    OoAction.Action = GeAction.kkRemoveLinkFromDiagram
                    OoAction.SetData(LoLink, "LINK")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkRemoveTableFromDiagram

                LeResult = MoAmodFile.DeleteTable(LoMMTableNode.Caption)
                If LeResult = GeActionResult.kkOk Then
                    Me.fcDiagram.Nodes.Remove(LoMMTableNode)
                End If

            Case GeAction.kkRemoveContainerFromDiagram
                Dim LoMMContainerNode As ClsMMContainerNode = OoAction.GetData("NODE")
                Dim LoNoteLinkCollection As Collection = New Collection
                Dim LoTableCollection As Collection = New Collection

                For Each LoLink As DiagramLink In LoMMContainerNode.GetAllLinks
                    Dim LoMMLinkNode As ClsMMLinkNode = CType(LoLink, ClsMMLinkNode)
                    Select Case LoMMLinkNode.MMTypeOfLink
                        Case GeTypeOfLink.kkNote
                            LoNoteLinkCollection.Add(LoLink)
                        Case Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkRemoveContainerFromDiagram - GetAllLinks")
                    End Select
                Next

                For Each LoMMTableNode As ClsMMTableNode In LoMMContainerNode.SubordinateGroup.AttachedNodes
                    LoTableCollection.Add(LoMMTableNode)
                Next


                'removing note links
                For Each LoLink As DiagramLink In LoNoteLinkCollection
                    OoAction.Action = GeAction.kkRemoveLinkFromDiagram
                    OoAction.SetData(LoLink, "LINK")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkRemoveContainerFromDiagram

                'removing all child tables
                For Each LoMMTableNode As ClsMMTableNode In LoTableCollection
                    OoAction.Action = GeAction.kkRemoveTableFromDiagram
                    OoAction.SetData(LoMMTableNode, "NODE")
                    LeResult = Execute(OoAction)
                Next
                OoAction.Action = GeAction.kkRemoveContainerFromDiagram

                LeResult = MoAmodFile.DeleteUnit(LoMMContainerNode.Caption)
                If LeResult = GeActionResult.kkOk Then
                    Me.fcDiagram.Nodes.Remove(LoMMContainerNode)
                End If

            Case GeAction.kkCreateTemplate
                Try
                    Dim LoMMTableNode As ClsMMTableNode
                    LoMMTableNode = CType(fcDiagram.ActiveItem, ClsMMTableNode)
                    If LoMMTableNode IsNot Nothing Then
                        'checking duplicity
                        If UcnNodesToolbarUC.GetTemplate(LoMMTableNode.Caption) Is Nothing Then
                            'node from form
                            fcDiagramView.CopyToClipboard(False, False)
                            'same node in toolbar
                            UcnNodesToolbarUC.DiagramView.PasteFromClipboard(0, 0, False)

                            'creating datatable for data from table _a_Columns as copy of rows
                            Dim LoDataTable As DataTable = New DataTable
                            LoDataTable = MoAmodFile.Dataset.Tables("_a_Columns").Clone 'creating schema
                            Dim LoDataRows() As DataRow = MoAmodFile.GetColumnsOfTable(LoMMTableNode.Caption, "Position ASC")
                            For Each LoDataRow As DataRow In LoDataRows
                                Dim LoNewRow As DataRow = LoDataTable.NewRow
                                LoNewRow.ItemArray = LoDataRow.ItemArray
                                LoDataTable.Rows.Add(LoNewRow)
                            Next
                            'setting of tag
                            UcnNodesToolbarUC.GetTemplate(LoMMTableNode.Caption).Tag = LoDataTable
                            'saving
                            UcnNodesToolbarUC.SaveToolbar()
                            UcnNodesToolbarUC.RefreshToolbar()
                            LeResult = GeActionResult.kkOk
                        Else
                            Debug.Print("CHYBA!!! - Execute - ACTION - kkCreateTemplate - GetTemplate")
                            LeResult = GeActionResult.kkError
                        End If
                    Else
                        Debug.Print("CHYBA!!! - Execute - ACTION - kkCreateTemplate - LoMMTableNode Is Nothing")
                        LeResult = GeActionResult.kkError
                    End If
                Catch ex As Exception
                    LeResult = GeActionResult.kkError
                End Try
        End Select
        '---------------------------------------------
        'ACTION AFTER ACTION
        '---------------------------------------------
        Select Case OoAction.Action
            Case GeAction.kkNewFile, GeAction.kkOpenFile, GeAction.kkCloseFile
                If LeResult = GeActionResult.kkOk Then SetEnableAfterChangeOfStateOfFile()
            Case GeAction.kkSaveFile
                If LeResult = GeActionResult.kkOk Then
                    SetCaptionOfForm()
                    SetEnableMenu()
                End If
        End Select


        '---------------------------------------------
        Return LeResult
        '---------------------------------------------

    End Function
    '#######################################
#End Region


    ' ''Console.WriteLine([Enum].GetName(GetType(kkComponentTypes), kkComponentTypes.kkxGrid))
    ' ''Dim a As String() = [Enum].GetNames(GetType(kkComponentTypes)) '- pole retazcov


End Class